Game Development Reference
In-Depth Information
This class is a container that will hold a sprite for every life the player currently has. It accepts one parameter in
its constructor, numLives , which is assigned to the one and only property on the class. The initialize method then
calls on two functions, the first creates the sprites for the container and the second positions it.
A loop is created based on the number of lives that the game will give the player at the start of the game. During
the loop, a life sprite is created, paused, added to the container, and then positioned accordingly in a horizontal
fashion. The container itself is then positioned at the bottom right corner of the game in the positionBox function.
When a player loses a life, the removeLife method is called. The first child, which will always be the left-most
sprite, is referenced and its animation frames are played. A listener is set on this animation, which will stop when
complete, and then it is removed from the container. Figure 11-9 shows three lives in the LifeBox container.
Figure 11-9. The LifeBox HUD element
Using Object Pools
The technique of using object pools is common among game developers. The concept is simple. Instead of creating
a new instance of something every time you need one, you create several of them right away and stick them into an
array. When you need the object, you grab it from this array. When you are finished with it, you put it back. To build
the game's object pools, you will be using a custom class that will create these pools (see Listing 11-11).
Listing 11-11. The SpritePool Class, Declared in SpritePool.js
(function () {
var SpritePool = function (type, length) {
this.pool = [];
var i = length;
while (--i > -1) {
this.pool[i] = new type();
}
}
SpritePool.prototype.getSprite = function () {
if (this.pool.length > 0) {
return this.pool.pop();
}
else {
throw new Error("You ran out of sprites!");
}
}
SpritePool.prototype.returnSprite = function (sprite) {
this.pool.push(sprite);
}
window.game.SpritePool = SpritePool;
}());
 
Search WWH ::




Custom Search