Finally, the linear velocity of an object is how fast and in which direction a
thing is moving. We start the avatar with a speed of 150 straight up. If the
avatar collides with some fruit, we also give the avatar a little bump of 50
straight up.
Uncomment the addAvatar() call in the code outline. We still have not created
the animate() function, so nothing is moving just yet. The “avatar” should be
resting on the ground. For now, it’s just a purple rectangle—we’ll make it a
little fancier later.
Add Scoring
Next we add the scoreboard:
functionaddScoreboard() {
varscoreboard =newScoreboard();
scoreboard.score(0);
scoreboard.help('Use arrow keys to move and the space bar to jump');
returnscoreboard;
}
This is similar to the scoreboard we used in Chapter 11, Project: Fruit Hunt,
on page 99, so the code should look familiar. Uncomment the addScoreboard()
function in the code outline, and you should see a scoreboard showing zero
points.
Animate the Scene
Now we should have a scoreboard with zero points and a lovely purple box
sitting on the ground. To make it do something, we move the renderer.render-
er(scene,camera) at the bottom of our code into our usual animate() function—this
time with a twist.
vargame_over = false;
functionanimate() {
if(game_over)return;
requestAnimationFrame(animate);
scene.simulate();// run physics
renderer.render(scene, camera);
}
New here is a check to see if the game is over. If it is, we return from the
function, which stops the animation. Also new in here is the scene.simulate()
line. As the comment suggests, that line is needed so that the physics library
can move things (make them jump, fall, roll) and check for collisions. Don’t
forget that line!
Chapter 15. Project: The Purple Fruit Monster Game • 138
Prepared exclusively for Michael Powell report erratum • discuss