3D Game Programming

(C. Jardin) #1
functionwalk() {
if(!isWalking())return;
varposition = Math.sin(clock.getElapsedTime()*5) * 50;
right_hand.position.z = position;
left_hand.position.z = -position;
right_foot.position.z = -position;
left_foot.position.z = position;
}

Did you notice the first line of the function? This line of code means if the
avatar is not walking, then return immediately from the function. Calling return
means that we leave the function immediately and that nothing else in the
function is run. That is, if the avatar is not walking, then leave the walk()
function without running any of the code that makes the avatar look like it is
walking.

If you’ve been paying very close attention, you might wonder what that
isWalking() thing is. It’s a function that we’ll write now!

We’ll add this code before the keydown event listener.


varis_moving_right, is_moving_left, is_moving_forward, is_moving_back;
functionisWalking() {
if(is_moving_right)returntrue;
if(is_moving_left)returntrue;
if(is_moving_forward)returntrue;
if(is_moving_back)returntrue;
returnfalse;
}

Immediately before the isWalking() function, we declare “is moving” variables
that will be used soon. We use a JavaScript shortcut—a comma-separated
list—for all four variables on a single line and with only one var.

Inside the function, we use the return keyword to exit immediately from the
function. This time we return a true or false value. If any of the movement
properties of the avatar controls are true, then isWalking() will return true. In
other words, if any of the movement properties of the controls say that the
avatar is moving, then the avatar isWalking().

The very last line of the function isWalking() that returns false, will be reached
only if none of the movement controls are true. If none of the movement
properties of the avatar controls are on, then we return false to let it be known
that the avatar is not walking.

Now we need to turn those movement controls on and off. We do this in the
event listener, where we’re already moving the avatar depending on the key
being pressed. Add the lines shown.

Chapter 6. Project: Moving Hands and Feet • 64


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf