3D Game Programming

(C. Jardin) #1
fruit.setLinearVelocity(
newTHREE.Vector3(-150, 0, 0)
);
}

There’s nothing new in the launchFruit() function. Its job is to create a physics-
ready circle, add it to the scene, and set it rolling. Much more interesting is
the gameStep() function, which we’ll use again in upcoming chapters.

After completing the gameStep() and launchFruit() functions, uncomment the call
to gameStep() in the code outline. If everything is working properly, you should
see pieces of red fruit rolling out toward the avatar. Once the avatar hits the
ground, the game should be over and the fruit should stop moving.

We have just one thing left to do in the basic game—add controls to our avatar.


Creating Avatar Controls


To control the avatar, we use the keydown event listener that we saw in earlier
chapters. Add the following code below the gameStep() and launchFruit() functions:

document.addEventListener("keydown",function(event) {
varcode = event.keyCode;

if(code == 37) left(); // left arrow
if(code == 39) right();// right arrow
if(code == 38) up(); // up arrow
if(code == 32) up(); // space bar
});

functionleft() { move(-50, 0); }
functionright() { move(50, 0); }
functionup() { move(avatar.getLinearVelocity().x, 50); }

functionmove(x, y) {
avatar.setLinearVelocity(
newTHREE.Vector3(x, y, 0)
);
}

With that, we should be able to move the avatar up, left, and right to eat
yummy fruit! (See Figure 8, Purple Box Monster, on page 141.)

Congratulations! You just wrote another game from scratch. To be sure,
there’s still a lot that you might want to do with the game:


  • Make the fruit move faster for higher scores

  • Add things that the purple fruit monster doesn’t like to make the score
    go down when he eats them


Chapter 15. Project: The Purple Fruit Monster Game • 140


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf