3D Game Programming

(C. Jardin) #1
Uncomment the animate() function (it’s before the final gameStep() call) from the
code outline. Nothing will change, but now we can add game controls.

Add Game Controls


We have the ball and the board now, so let’s add controls for the game board.
Add the following function definition of addControls() above the animate() function
we just added.

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

if(code == 37) left();
if(code == 39) right();
if(code == 38) up();
if(code == 40) down();
});
}

By now we’re very familiar with using JavaScript events to control gameplay.
We’re also starting to learn the computer numbers for the arrow keys by heart!

Notice that we need to define a few more functions to tilt the game board left,
right, up, and down. Add the following five function definitions.

functionleft() { tilt('z', 0.02); }
functionright() { tilt('z', -0.02); }
functionup() { tilt('x', -0.02); }
functiondown() { tilt('x', 0.02); }

functiontilt(dir, amount) {
board.__dirtyRotation = true;
board.rotation[dir] = board.rotation[dir] + amount;
}

The left(), right(), up(), and down() functions are pretty easy to understand. They
are so short that we can put the entire function definition on one line! What
we’re doing in the tilt() function called by each of those is a little trickier.

We already know what __dirtyRotation is from our work on __dirtyPosition in Add
the Game Ball (and we know that it starts with two underscore characters).
We’re changing the game board’s rotation. Even though the board’s rotation
is changing by only a tiny bit, we need to tell the physics library that we truly
want to do this.

What’s really sneaky in tilt() is board.rotation[dir]. When the left() function is called,
it calls tilt() with the string 'z' as the value for dir. In this case, it’s the same as

Chapter 16. Project: Tilt-a-Board • 152


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf