- If Math.random() is 1 , then 10Math.random() is 10 , making 20 + 10Math.random()
end up as 30.
In other words, since Math.random() is guaranteed to be between 0 and 1 , we’re
guaranteed of getting a number between 20 and 30.
The random numbers are wrapped in a Math.floor() function call. Math.floor()
removes everything after the decimal point. If Math.random() returns 0.01, then
10*Math.random() would wind up as 0.1. Math.floor() removes the decimal point and
everything after it, leaving us with 0.
The random number fetches a point from the river_points property to send to
addFruitPowerUp(). That function mostly does stuff that we’ve seen before—it
builds a physical mesh, assigns a collision event listener, and adds the yellow
fruit to the scene:
functionaddFruitPowerUp(location, ground, scoreboard) {
varmesh =newPhysijs.ConvexMesh(
newTHREE.SphereGeometry(10, 25),
newTHREE.MeshPhongMaterial({emissive: 0xbbcc00}),
0
);
mesh.receiveShadow = true;
mesh.castShadow = true;
mesh.addEventListener('collision',function() {
varlist_index = game_items.indexOf(mesh);
game_items.splice(list_index, 1);
scene.remove(mesh);
scoreboard.addPoints(200);
scoreboard.message('Yum!');
setTimeout(function() {scoreboard.clearMessage();}, 2.5* 1000);
});
ground.updateMatrixWorld();
varp =newTHREE.Vector3(location.x, location.y, -20);
ground.localToWorld(p);
mesh.position.copy(p);
scene.add(mesh);
returnmesh;
}
The first thing we do in the collision-handling function is remove the fruit
from the list of game items. JavaScript doesn’t make this easy—we get the
index (the location in the list) of the item to be removed, then remove it by
splicing from that index to the one following it. There is a famous JavaScript
book named JavaScript: The Good Parts—removing things from lists is defi-
nitely not in that book (which you should read).
Chapter 20. Project: River Rafting • 204
Prepared exclusively for Michael Powell report erratum • discuss