pushing nothing onto our list of trees. Add the following line to the very bottom
of the makeTreeAt() function before the last curly brace:
functionmakeTreeAt(x, z) {
// Don't change any code at the start...
// ... but add the following line to the end:
returntop;
}
With that, the treetop (the green ball/leaves) is returned to be added to the
list of trees. We could have returned the trunk or even the collision boundary
that we added in Project: Collisions. The top of the tree is what we need to
work with the most (as that is where the treasure will be hidden), so it makes
sense to return it so that it can be pushed into the list of trees.
Now that we have a list of trees, we can hide treasure in one and shake it.
After the makeTreeAt() function, add the following function and function call:
functionshakeTree() {
tree_with_treasure = Math.floor(Math.random() * trees.length);
newTWEEN
.Tween({x: 0})
.to({x: 2*Math.PI}, 200)
.repeat(20)
.onUpdate(function() {
trees[tree_with_treasure].position.x = 75 * Math.sin(this.x);
})
.start();
setTimeout(shakeTree, 12*1000);
}
shakeTree();
We’ll talk about Math.floor() and Math.random() in Chapter 20, Project: River Rafting,
on page 185. For now, let’s leave it that the first line in shakeTree() picks a random
tree.
We’ve already met the Tween library, which moves things from one value to
another. In this case, we again move along a sine curve. Sines and cosines are
great because they start and end at the same value when moving from zero
to 360° (2*Math.PI). We use the sine.
As the value of the Tween moves from 0 to 2*Math.PI, the value of Math.sin() goes
from 0 to 1 , then back to 0 , then to -1, and finally back to 0. In other words,
it’s perfect to make things wiggle a little.
Chapter 11. Project: Fruit Hunt • 102
Prepared exclusively for Michael Powell report erratum • discuss