3D Game Programming

(C. Jardin) #1

The checkForTreasure() function does three things:



  • If there is no active tree—if it is undefined, as described in Describing a
    Thing in JavaScript—then it returns immediately and does nothing else.

  • If there is an active tree near the avatar, then checkForTreasure() calculates
    the distance between the tree and the avatar.

  • If the distance is less than 500 , then the scorePoints() function is called.


Pythagorean Theorem Alert
If you have already learned a little bit of trigonometry, you may
have recognized the Pythagorean theorem in the checkForTreasure()
function. We used it to find the distance between two points: the
avatar and the active tree.

For now, we’ll keep the scorePoints() function very simple. Add it after the
checkForTreasure() function. We’ll use it only to add points to the scoreboard:

functionscorePoints() {
if(scoreboard.getTimeRemaining() === 0)return;
scoreboard.addPoints(10);
}

Be sure to add the first line in that function; otherwise players can get points
after time has expired!

The last thing we need to do is animate the jump so we can see it on the
screen. We combine two things that we’ve seen before: Tweens and a sine
function. Let’s add the animateJump() function next:

functionanimateJump() {
newTWEEN
.Tween({jump: 0})
.to({jump: Math.PI}, 500)
.onUpdate(function() {
marker.position.y = 200* Math.sin(this.jump);
})
.start();
}

That should do it! If you hide the code, you can now move about, find the
active tree, and jump to get treasure out of it. If you are very fast, you can
even jump multiple times next to the active tree to get multiple points.

This is already a fun game, but we can add a few tweaks to make it even
better.

Chapter 11. Project: Fruit Hunt • 104


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf