3D Game Programming

(C. Jardin) #1
Ramp.prototype.rotate =function(angle) {
this.mesh.rotation.z = this.mesh.rotation.z + angle;
this.mesh.__dirtyRotation = true;
this.mesh.__dirtyPosition = true;
};

Next is the listenForEvents() method, which is where all of the action really takes
place:

Ramp.prototype.listenForEvents =function() {
varme = this,
mesh = this.mesh;
mesh.addEventListener('drag',function(event) {
me.move(event.x_diff, event.y_diff);
});

document.addEventListener('keydown',function(event) {
if(!mesh.isActive)return;
if(event.keyCode != 83)return;// S
me.rotate(0.1);
});
};

We start this method by assigning a new me variable to this and a new mesh
variable to this.mesh. We do this mostly because JavaScript can do strange
things to this—especially when dealing with events. JavaScript has very good
reasons for messing with this, but we’re not going to worry about them in this
book.

First we listen for drag events, which occur when the game player clicks and
drags something. In this case, the ramp is dragged by the amounts event.x_diff
and event.y_diff, and we tell the ramp to move itself with the move() method that
we already made.

Next, if the game player clicks a ramp (making it active) and presses the S
key, then we rotate the ramp by a little bit.

Both the drag event and the isActive property come from the Mouse.js library
that we added in Section 18.1, Getting Started, on page 165. Without that
library, neither of those will work.

That’s it! We now have a way to construct as many ramps as we like. Each
ramp that we construct will have its own mesh and will move by itself. To see
this in action, let’s create two ramps and add their meshes to the scene:

varramp1 =newRamp(-width/4, height/4);
scene.add(ramp1.mesh);
varramp2 =newRamp(width/4, -height/4);
scene.add(ramp2.mesh);

report erratum • discuss

Building Draggable Ramps • 173


Prepared exclusively for Michael Powell

Free download pdf