3D Game Programming

(C. Jardin) #1
a number between 0 and 1. So, if the random number is less than 0.33, we
place the goal in the top-left corner (width/-2, height/2). If the random number is
greater than 0.66, we place the goal in the top-right corner (width/2, height/2).
Otherwise we place the goal in the middle of the cave ceiling (0, height/2).

functionplaceGoal() {
varx = 0,
rand = Math.random();
if(rand < 0.33) x = width / -2;
if(rand > 0.66) x = width / 2;
goal.position.set(x, height/2, 0);
scene.add(goal);
}
placeGoal();

We make this a function so that we can call it again and again. When we add
multiple levels to the game in the next chapter, we’ll need to call placeGoal()
whenever the player completes a level. The same goes if we add a game-reset
capability.

If you update the code several times, you should see the goal move to different
places at the top of the screen. Of course, none of this matters yet—there’s
no way for the avatar to get to the top of the screen!

Let’s add a way.


18.4 Building Draggable Ramps


It is a long way up to the top of the screen. game players are going to need
at least two ramps to reach the top. To build two ramps that behave the same
way but are separate, we’ll need to construct some JavaScript objects as we
did in Chapter 17, Project: Learning about JavaScript Objects, on page 159.

report erratum • discuss

Building Draggable Ramps • 171


Prepared exclusively for Michael Powell

Free download pdf