3D Game Programming

(C. Jardin) #1
document.addEventListener("keydown",function(event) {
varcode = event.keyCode;
if(code == 32) pushRaft(); // space
if(code == 37) rotateRaft(-1);// left
if(code == 39) rotateRaft(1); // right
if(code == 82) startGame(raft, river, scoreboard);// R
});

functionpushRaft() {
varangle = raft.rotation.z;

raft.applyCentralForce(
newTHREE.Vector3(
500 * Math.cos(angle),
0,
-500 * Math.sin(angle)
)
);
}

functionrotateRaft(direction) {
raft.__dirtyRotation = true;
raft.rotation.z = raft.rotation.z + direction * Math.PI/10;
}

We’ve seen keyboard listeners a lot by this point, so document.addEventListener()
should already be familiar. The pushRaft() function uses a new method for
physics objects: applyCentralForce(). This is just a fancy way of saying “push a
thing from the middle and not the edge.” Lastly, the rotation, including
__dirtyRotation, should be familiar—we last saw it in Chapter 18, Project: Cave
Puzzle, on page 165.

With that, we have the basic pieces of a pretty cool game! The left and right
arrow keys will turn the raft and the space bar will push the raft forward in
the direction it’s facing.

We can do a lot more with this game. We’ll add simple scoring and an obstacle
or two in the river.

20.5 Setting the Finish Line


Eventually the raft reaches the finish line. And then it keeps right on going.
And going. Instead, let’s pause the game so that players can take a moment
to admire their score before trying again. We need to make changes in four
places: in our code outline and in startGame(), animate(), and gameStep().

Let’s start with the code outline. Before the call to the startGame() function, we
need to add a line for the paused variable:

Chapter 20. Project: River Rafting • 198


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf