Game Development Reference
In-Depth Information
This example combines Math.random and Math.floor to generate a random number that is 0, 1, or 2:
var randomval = Math.floor(Math.random() * 3);
Using this approach, you can calculate a random value and then use an if instruction to select a
color for the paint can. This task is done by the calculateRandomColor method. Here is what the
method looks like:
PaintCan.prototype.calculateRandomColor = function () {
var randomval = Math.floor(Math.random() * 3);
if (randomval == 0)
return sprites.can_red;
else if (randomval == 1)
return sprites.can_green;
else
return sprites.can_blue;
};
Now that you've programmed these two methods for generating random values, you can use them
when you define the behavior of the paint can.
Updating the Paint Can
The update method in the PaintCan class should do at least the following things:
Set a randomly created velocity and color if the can currently is not yet falling
Update the can position by adding the velocity to it
For the first task, you can use an if instruction to check whether the can currently is not moving
(the velocity equals zero). Furthermore, you want to introduce a bit of unpredictability for when the
can appears. In order to achieve that effect, you assign a random velocity and color only if some
generated random number is smaller than a threshold of 0.01. Because of the uniform distribution,
only in approximately 1 out of 100 random numbers will the number be smaller than 0.01. As a
result, the body of the if instruction will only be executed sometimes, even when a can's velocity is
zero. In the body of the if instruction, you use the two methods you defined earlier for generating a
random velocity and a random color:
Check whether the can has fallen completely, and reset it in that case
if (this.velocity.y === 0 && Math.random() < 0.01) {
this.velocity = this.calculateRandomVelocity();
this.currentColor = this.calculateRandomColor();
}
You also need to update the can position by adding the current velocity to it, again taking into
account the elapsed game time, just as you did with the ball:
this.position.x = this.position.x + this.velocity.x * delta;
this.position.y = this.position.y + this.velocity.y * delta;
 
Search WWH ::




Custom Search