Game Development Reference
In-Depth Information
Adding Glitters
A glitter field is a rectangle containing multiple glitters, depending on the desired density. Therefore,
you need an array to maintain where these glitters should be drawn. This is done in the member
variable positions , which is an array that is initialized in the constructor:
this.positions = [];
You fill this list with a number of randomly generated positions. To randomly generate a position
within the field, you can add a method createRandomPosition that does this work for you. The
method is straightforward; you simply generate a random position within the glitter rectangle:
GlitterField.prototype.createRandomPosition = function () {
return new Vector2(Math.random() * this.width, Math.random() *
this.height);
};
To fill the position array with random values, you use a for instruction:
for (var i = 0; i < density; i++) {
this.positions.push(this.createRandomPosition());
}
To draw the glitters, you need more than just a position. You want to add a visual effect that lets
the glitters appear and disappear smoothly. You achieve that by drawing them at a scale that first
increases and then decreases. This means you also need to maintain the current scale for each
of the glitters you're drawing. You do this in another array of variables called scales , which is also
initialized in the constructor:
this.scales = [];
Every time you add a new position to the positions array, you also add a scale of 0 to the scales
array. So the final for instruction becomes
for (var i = 0; i < density; i++) {
this.positions.push(this.createRandomPosition());
this.scales.push(0);
}
Updating the Glitter Field
In the constructor, you set the scale for each glitter to 0. The result is that when the glitters are
drawn, they aren't visible to the player. In the update method, you increase and decrease this scale
again until it returns to zero. When that happens, you generate another random position for that
glitter so it appears elsewhere. Add the following two member variables to the GlitterField class:
this._scaleMax = 1;
this._scaleStep = 0.05;
 
Search WWH ::




Custom Search