3D Game Programming

(C. Jardin) #1
The Tween library animates changes between a start and end. Here we want
to animate starting with one rotation and moving to an ending rotation.

The first step in using Tween is to add its update() function to our animate()
function:

functionanimate() {
requestAnimationFrame(animate);
TWEEN.update();
walk();
turn();
acrobatics();
renderer.render(scene, camera);
}
animate();

Next we need to change the function turn() that we just wrote. Instead of setting
the direction right away, we’ll call a new function that will spin the avatar in
the new direction. Change the last line of the function turn() to call spinAvatar():

functionturn() {
vardirection = 0;
if(is_moving_forward) direction = Math.PI;
if(is_moving_back) direction = 0;
if(is_moving_right) direction = Math.PI/2;
if(is_moving_left) direction = -Math.PI/2;

spinAvatar(direction);
}

Last, we need to write the code for the spinAvatar() function. The Tween code
might seem a little strange at first. When reading it, keep in mind that we
want to start the spin where the avatar’s head is currently facing (avatar.rota-
tion.y). We want to end in the new direction that is sent into spinAvatar() as the
direction argument.

Write the following spinAvatar() function after the turn() function:


functionspinAvatar(direction) {
newTWEEN.
Tween({y: avatar.rotation.y}).
to({y: direction}, 100).
onUpdate(function() {
avatar.rotation.y = this.y;
}).
start();
}

Reading from top to bottom in that function, the new Tween starts with a Y
rotation value of avatar.rotation.y—the direction the avatar is already facing. We

report erratum • discuss

Animating the Spin • 83


Prepared exclusively for Michael Powell

Free download pdf