3D Game Programming

(C. Jardin) #1
The last part of shakeTree() sets a timeout for 12 seconds. After 12 seconds
have passed, this timeout calls the shakeTree() function again and assigns a
new tree with the treasure.

After this code, a different tree should be wiggling uncontrollably telling the
player that there is treasure to be collected. Let’s give the avatar a way to
grab that treasure.

11.4 Jumping for Points


In this game, the avatar needs to jump next to the current treasure-filled tree.
We’ll do two things when this happens: the avatar will score some points and
we’ll make a nice little animation of the treasure and play a sound.

But first we need a key that will start a jump. We do this by adding the follow-
ing if statement to the keydown() listener:

if(code == 32) jump(); // space

You can add that if code just above the other if statements that turn the avatar.


Now we add the jump() function that the case statement calls. This function
can go after the detectCollisions() function. It checks for treasure and animates
the jump on our screen:

functionjump() {
checkForTreasure();
animateJump();
}

To check whether the avatar is close enough to grab treasure, add the following
function at the bottom of the code (just above the last <script/> tag):

functioncheckForTreasure() {
if(tree_with_treasure == undefined)return;

vartreasure_tree = trees[tree_with_treasure],
p1 = treasure_tree.parent.position,
p2 = marker.position;

vardistance = Math.sqrt(
(p1.x - p2.x)*(p1.x - p2.x) +
(p1.z - p2.z)*(p1.z - p2.z)
);

if(distance < 500) {
scorePoints();
}
}

report erratum • discuss

Jumping for Points • 103


Prepared exclusively for Michael Powell

Free download pdf