3D Game Programming

(C. Jardin) #1
Once the animate() function is ready, move back up to the code outline and
uncomment the call to animate(). If everything is working, the avatar should
jump up into the air and fall down to the ground, and the game should end.

Create Game Elements


So far, we have no fruit for the purple fruit monster to eat. We add this in the
gameStep() function. We haven’t seen this before, but it’s very useful in 3D
game programming. The animation and physics are working hard. We don’t
want to interrupt them every time they’re doing something to decide if it’s
time to start rolling another piece of fruit.

So we use a separate gameStep() function, which runs every three seconds.
Type in the following below the animate() function:

functiongameStep() {
if(game_over)return;

launchFruit();
setTimeout(gameStep, 3*1000);
}

The first time gameStep() is called, we launch some fruit at the avatar with the
launchFruit() function. After a timeout of 3 seconds, this function calls itself
again, which launches another piece of fruit. Telling a function to take a “time-
out” until it does something else is the job of setTimeout(). The setTimeout() function
is built into JavaScript to wait for some period of time, in milliseconds, before
calling the function that it’s given. In this case, gameStep() calls itself after
3*1000 milliseconds, or after 3 seconds.

Just like with the animate() function, we return immediately from gameStep() if
the game is over.

Of course, none of this will work unless we define the function that launches
the fruit:

functionlaunchFruit() {
varfruit =newPhysijs.ConvexMesh(
newTHREE.CylinderGeometry(20, 20, 1, 24),
newTHREE.MeshBasicMaterial({color: 0xff0000})
);

fruit.is_fruit = true;
fruit.setAngularFactor(newTHREE.Vector3( 0, 0, 1 ));
fruit.setLinearFactor(newTHREE.Vector3( 1, 1, 0 ));
fruit.position.set(300, 20, 0);
fruit.rotation.x = Math.PI/2;
scene.add(fruit);

report erratum • discuss

Outline the Game • 139


Prepared exclusively for Michael Powell

Free download pdf