3D Game Programming

(C. Jardin) #1
raft.position.set(start.y, start.z + 100, 0);
raft.setLinearVelocity(newTHREE.Vector3());
scoreboard.resetTimer();
scoreboard.score(0);
updateCamera();
camera.lookAt(newTHREE.Vector3(start.y, 0, 0));
}

Don’t forget that __dirtyPosition starts with two underscore characters!


The code in this function has to work for both starting the game and restarting
the game. The setLinearVelocity() call sets the speed of the raft to zero every time
it’s called. Without that, a player restarting the game midway through a race
would restart at the starting line already at full speed.

Aside from placing the raft at the starting line and resetting the scoreboard,
this code repositions the camera by first moving it, then telling it to look at
the starting line. updateCamera() moves the camera; it’s a new function that we
need to add to our code just below the startGame() function:

functionupdateCamera() {
camera.position.set(
raft.position.x + 75,
raft.position.y + 40,
raft.position.z
);
}

We make updateCamera() a separate function so that animate() can call it every
time the scene gets updated. We add a call to updateCamera() just above the line
with renderer.render() in animate(), as shown here:

functionanimate() {
requestAnimationFrame(animate);

updateCamera();
renderer.render(scene, camera);
}
animate();

This ensures the camera will be in front of the raft every time the scene is
rendered.

At this point you should have a raft moving down the river, with the camera
watching it the whole way. Of course, this is pretty useless without controls.

The following keyboard listener and two functions give the game some basic
controls. Add them at the very bottom of your code (before the final </script>
tag).

report erratum • discuss

Build a Raft for Racing • 197


Prepared exclusively for Michael Powell

Free download pdf