Game Development Reference
In-Depth Information
The ordering of the jewels in the image file is important in this case, as you see later. When you
create a Jewel instance, you randomly choose which jewel to represent by storing a random number
between 0 and 26 (to cover the 27 varieties) in a member variable variation . Therefore, the Jewel
constructor becomes
function Jewel(layer, id) {
SpriteGameObject.call(this, sprites.jewels, layer, id);
this.variation = Math.floor(Math.random() * 27);
}
Because the Jewel class knows which sprite it's going to use, you pass the sprite ( sprites.jewels )
directly to the base class constructor.
Now the only thing that needs to be modified is the draw method. You don't want to draw the entire
sprite, but only a part of it: the part that contains the jewel this object represents. For this, you first
have to extend the Canvas2D.drawImage method, because it needs to be able to draw only part of
a sprite. Fortunately, this is straightforward to do. The drawImage method of the HTML5 canvas
element has four parameters with which you can specify the part of the sprite you want to draw. To
indicate which part of the sprite you want to draw, you use a Rectangle object. The header of the
Canvas2D.drawImage method is as follows:
Canvas2D_Singleton.prototype.drawImage = function (sprite, position, rotation,
scale, origin, sourceRect)
The last parameter of the method is the rectangle that defines which part of the source image should
be drawn. In the method body, you use the member variables of this Rectangle object as follows:
this._canvasContext.drawImage(sprite, sourceRect.x, sourceRect.y,
sourceRect.width, sourceRect.height, -origin.x * scale, -origin.y * scale,
sourceRect.width * scale, sourceRect.height * scale);
The second through fifth parameters indicate what part of the image should be drawn. The last two
parameters indicate the width and height of the projection of that image on the canvas. You multiply
the width and height of the rectangle by the scale, so that the image drawn can be scaled by the
user if desired. Because you're scaling the sprite, you also need to scale the origin, which happens
in the third code line.
In the draw method of the Jewel class, you need to determine which part of the jewel sprite you want
to draw depending on the value of the variation member variable:
var imagePart = new Rectangle(this.variation * this.height, 0, this.height,
this.height);
Here the segment you want to draw is a square shape that has the same width and height as the
height of the original sprite. The position of the rectangle (given by the first two parameters in the
Rectangle constructor) is calculated by multiplying the height of the sprite by the variation index.
 
Search WWH ::




Custom Search