3D Game Programming

(C. Jardin) #1
We start by defining our ramp constructor. Since it constructs objects, we
capitalize the name of the constructor function as Ramp. In the constructor,
we define one property, the ramp mesh, and call three methods:

functionRamp(x, y) {
this.mesh =newPhysijs.ConvexMesh(
newTHREE.CylinderGeometry(5, height * 0.05, height * 0.25),
Physijs.createMaterial(
newTHREE.MeshBasicMaterial({color:0x0000cc}), 0.2, 1.0
),
0
);

this.move(x, y);
this.rotate(2*Math.PI*Math.random());
this.listenForEvents();
}

We know meshes by now, so there’s not much to say about this one. As in
Project: The Purple Fruit Monster Game, we make this one a Physijs mesh so
that the avatar can speed up the ramp.

The three methods we call at the end of the constructor help us to initialize
a new ramp. The this.move() method moves the ramp by the amount specified
in the constructor. If we make a new ramp with new Ramp(100, 100), then
this.move(x, y) would move the ramp to X=100, Y=100. Next, we rotate the ramp
by a random amount. Last, we tell our ramp object that it needs to listen for
events. Let’s look at each of those methods in turn.

The move() method expects two number parameters that tell it by how much
the ramp needs to be moved:

Ramp.prototype.move =function(x, y) {
this.mesh.position.x = this.mesh.position.x + x;
this.mesh.position.y = this.mesh.position.y + y;
this.mesh.__dirtyRotation = true;
this.mesh.__dirtyPosition = true;
};

When we move a ramp, we’re defying physics—one moment the ramp can be
in the middle of the screen with no rotation and the next it can be at X=100,
Y=100 and rotated randomly. Any time we do this, we have to tell the physics
engine that we’re doing something non-physics, which is why we set __dirtyPo-
sition and __dirtyRotation. Don’t forget that, as in Add the Game Ball, on page 148,
there are two underscores before both of those “dirty” variables.

The rotate() method is very similar:


Chapter 18. Project: Cave Puzzle • 172


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf