functionmove(x) {
varv_y = avatar.getLinearVelocity().y,
v_x = avatar.getLinearVelocity().x;
if(Math.abs(v_x + x) > 200)return;
avatar.setLinearVelocity(
newTHREE.Vector3(v_x + x, v_y, 0)
);
}
This move() function is pretty intelligent. First it determines how fast the avatar
is already moving. We need to know how fast the avatar is moving left or right
so that we can increase or decrease the speed (depending on which arrow key
is pressed). We also need to know how fast the avatar is moving up or down
so that we do not change it. It wouldn’t make sense for a falling avatar to all
of a sudden stop falling.
We also do something a little sneaky in here. We set it up so that the avatar
can never go faster than 200. The Math.abs() function strips negatives from
numbers (maybe you’ve seen absolute value in your math class—that’s what
abs stands for here). In other words Math.abs(-200) equals 200 —just like
Math.abs(200). This lets us say, “if the avatar’s speed is -200 (moving left) or 200
(moving right), then do not change the speed at all.” The player needs to win
the game with a speed no faster than 200.
That’s it for the avatar. Now let’s add the goal.
18.3 Building a Random, Unreachable Goal
Let’s make the goal a green donut. Don’t forget to wrap the normal 3D mesh
inside the physics mesh for easy collisions.
vargoal =newPhysijs.ConvexMesh(
newTHREE.TorusGeometry(100, 25, 20, 30),
Physijs.createMaterial(
newTHREE.MeshBasicMaterial({color:0x00bb00})
),
0
);
goal.isGoal = true;
The very last line is how we tell the avatar that this is the goal. We created
the avatar’s collision detection so that it checked for this isGoal property.
Nothing else in our game has this property set, which lets us be certain that
the avatar really has reached the goal.
Next we do something a little different: we place the goal at one of three ran-
dom locations. In JavaScript, a random number comes from Math.random(). It’s
Chapter 18. Project: Cave Puzzle • 170
Prepared exclusively for Michael Powell report erratum • discuss