3D Game Programming

(C. Jardin) #1
So let’s make this happen. Remove the alert(event.keyCode) line inside the docu-
ment.addEventListener(). Replace it with the following code, starting with the var
code statement.

document.addEventListener('keydown',function(event) {
varcode = event.keyCode;
if(code == 37) avatar.position.x = avatar.position.x-5;// left
if(code == 38) avatar.position.z = avatar.position.z-5;// up
if(code == 39) avatar.position.x = avatar.position.x+5;// right
if(code == 40) avatar.position.z = avatar.position.z+5;// down
});

We saw the if statement in Project: Making an Avatar. In this case, we’re
checking if the keycode is equal to one of the arrow-key computer numbers.
If the key code is 37 (left arrow key), then we change the avatar’s X position
by subtracting 5.

A double equals (==) in JavaScript checks if something is equal to something
else—a single equal (=) makes a value equal to something else. In our preceding
code example, we make code equal to event.keyCode. Then we check to see if it
is equal to the different arrow-key values.

Give It a Try!
Press the Hide Code button and give it a try. Use the arrow keys to
move the avatar around. Does it work like you expect?

Remember: If something goes wrong, check the JavaScript console!


If everything is working correctly, then you should be able to move your avatar
far away, up close, all the way to the left or right, and even off the screen.

You learned how to make sure the avatar’s hands and feet move with the
body when we added the ability to do cartwheels back in Section 3.6, Doing
Cartwheels, on page 32. Since the hands and feet were added to the avatar
object instead of the scene, moving the avatar means that the hands and feet
go along with it.

Chapter 4. Project: Moving Avatars • 38


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf