HTML and CSS Reference
In-Depth Information
Creating the Three Principle Objects
The game needs three principle, mostly persistent objects: a Game object tying everything together; a
SpriteSheet object for loading and drawing sprites; and a GameBoard object for displaying, updating, and
handling the collision of sprite elements. The game also needs a gaggle of different sprites such as the player,
enemies, missiles, and HUD objects, such as the score and number of remaining lives, but those are introduced
individually later.
Loading the SpriteSheet
You have already seen most of the code necessary to load a sprite sheet and display sprites on the page. All that
remains is to extract the functionality into a package. One enhancement puts in a map of sprite names to their
locations to make it easier to draw the sprites on the screen. A second enhancement encapsulates the onload
callback functionality to hide the details from any calling classes.
Listing 1-5 shows the entire class.
Listing 1-5: The SpriteSheet class
var SpriteSheet = new function() {
this.map = { };
this.load = function(spriteData,callback) {
this.map = spriteData;
this.image = new Image();
this.image.onload = callback;
this.image.src = 'images/sprites.png';
};
this.draw = function(ctx,sprite,x,y,frame) {
var s = this.map[sprite];
if(!frame) frame = 0;
ctx.drawImage(this.image,
s.sx + frame * s.w,
s.sy,
s.w, s.h,
x, y,
s.w, s.h);
};
}
Although the class is short and has only two methods, it does have a number of things to note. First, because
there can be only one SpriteSheet object, the object is created with
new function() { ... }
This puts the constructor function and the new operator on the same line, ensuring that only one instance of
this class is ever created.
 
 
Search WWH ::




Custom Search