Game Development Reference
In-Depth Information
The first variable specifies the maximum scale for the glitters (1 is the original size). The second
variable, _scaleStep , indicates how fast the scale should increase or decrease.
You don't want to begin increasing each glitter's scale at the same time—you want the glitters to
appear randomly. So, in the update method, you iterate through all the glitter positions and scales in
the list and, depending on the value of a random number, start increasing the scale:
for (var i = 0; i < this.scales.length; i += 1) {
if (this.scales[i] === 0 && Math.random() < 0.01)
this.scales[i] += this._scaleStep;
}
You only begin increasing the scale if it's zero and the random number value is smaller than 0.01. This
ensures that not all of the scales increase immediately. When a scale isn't zero anymore, you increase it:
else if (this.scales[i] !== 0) {
this.scales[i] += this._scaleStep;
// more code to come here
}
You can't infinitely increase the scale—you want to decrease it again. But how do you know if you
should increase or decrease the scale? You don't know in the update method whether you're in the
increasing part of the slope or the decreasing part. You can use a trick here: let the scale run from
zero to two times the maximum scale , and then, in the draw method, calculate the real scale from
that value (zero to maximum scale means increasing scale, and maximum scale to two times the
maximum scale means decreasing scale). In the update method, you add an if instruction to deal
with the situation when the scale is larger than twice the maximum scale:
if (this.scales[i] >=this._scaleMax * 2) {
this.scales[i] = 0;
this.positions[i] = this.createRandomPosition();
}
When that happens, you reset the scale to zero and generate a new random position for a new glitter.
Drawing the Glitter Field
In the draw method of the glitter field, you have to draw all the glitters on the screen at the desired
scale. You want to draw these glitters with their origin at the center, because otherwise the scaling
animation won't give the desired result. So, you calculate this origin once at the beginning of the
method call:
var origin = new Vector2(sprites.glitter.width / 2,
sprites.glitter.height / 2);
 
Search WWH ::




Custom Search