3D Game Programming

(C. Jardin) #1
avatar.position.set(-50, 50, 0);
scene.add(avatar);

avatar.setAngularFactor(newTHREE.Vector3( 0, 0, 0 ));// no rotation
avatar.setLinearFactor(newTHREE.Vector3( 1, 1, 0 )); // only move on X/Y axes
avatar.setLinearVelocity(newTHREE.Vector3(0, 150, 0));
avatar.addEventListener('collision',function(object) {
if(object.is_fruit) {
scoreboard.addPoints(10);
avatar.setLinearVelocity(newTHREE.Vector3(0, 50, 0));
scene.remove(object);
}
if(object == ground) {
game_over = true;
scoreboard.message("Game Over!");
}
});
returnavatar;
}

We’re familiar with JavaScript event listeners from Chapter 4, Project: Moving
Avatars, on page 35, where we used them to listen for keys being pressed on
the keyboard. Here we’re listening for something different: the purple fruit
monster colliding with something.

If the avatar collides with fruit, we add 10 points to the score, give the avatar
a little bump up, and remove the fruit from the screen (because the purple
fruit monster ate the fruit). If the avatar collides with the ground, then the
game is over and the purple fruit monster can eat no more.

There’s a lot going on in that function. The most important is the collision
event listener. This is where all the action takes place.

Several other new things in that function are worth mentioning. First is a
THREE.Vector3(). If you have seen the movie Despicable Me, then you know that
a vector is an arrow with direction and magnitude (Oh, yeah!). That means a
vector includes two pieces of information: the direction in which it points and
how strongly it points in that direction. You would use a vector to describe
how hard you would need to jump to reach a ledge that is up and to the left.

Vectors are very important in physics, which is why they’re used with Physijs
things. As the comments suggest, setting the “angular factor” to a vector of
all zeros prevents our avatar from rotating. Setting the “linear factor” is a way
to prevent motion up, down, left, right, forward, or backward. Since we want
our avatar to move only up, down, left, and right (but not into or out of the
screen), we set the X and Y components of the vector to 1 (allow motion) and
the Z component to 0 (don’t allow motion).

report erratum • discuss

Outline the Game • 137


Prepared exclusively for Michael Powell

Free download pdf