HTML and CSS Reference
In-Depth Information
abstractions, all things that don't make your game better necessarily but make your life as a game developer
better.
In Alien Invasion , the main culprits of duplication in these three sprite classes are the boilerplate setup code
and the draw method, which is the same across all three methods. It's time to extract those into a base object
called Sprite , which can handle initialization given a set of setup parameters as well as a sprite to use. Inside
the Enemy constructor, the three loops to copy one object into another is also a good opportunity for refactor-
ing.
If you haven't done a lot of prototypical inheritance in JavaScript, the syntax may look strange. Because
JavaScript doesn't have the idea of classes, instead of defining a class that represents the inherited properties,
you create a prototype object where JavaScript will look when a parameter isn't defined on the actual object.
Creating a Generic Sprite Class
In this section you create the Sprite object that all other sprites inherit from. Open up engine.js and add
the following code shown in Listing 2-4 :
Listing 2-4: A Generic Sprite Object
var Sprite = function() { }
Sprite.prototype.setup = function(sprite,props) {
this.sprite = sprite;
this.merge(props);
this.frame = this.frame || 0;
this.w = SpriteSheet.map[sprite].w;
this.h = SpriteSheet.map[sprite].h;
}
Sprite.prototype.merge = function(props) {
if(props) {
for (var prop in props) {
this[prop] = props[prop];
}
}
}
Sprite.prototype.draw = function(ctx) {
SpriteSheet.draw(ctx,this.sprite,this.x,this.y,this.frame);
}
This code goes into engine.js because it's generic engine code versus game-specific code. The construct-
or function is empty because each sprite has its own constructor function, and the Sprite object is created
only once for each of the descendant sprite object definitions. Constructor functions in JavaScript don't work
the same as constructors in other OO languages such as C++. To get around this, you need a separate setup
function to be called explicitly in the descendant objects.
This setup method takes in the name of the sprite in the SpriteSheet and a properties object. The sprite
is saved in the object, and then properties are copied over into the Sprite . The width and height are also set
here as well.
 
 
Search WWH ::




Custom Search