Game Development Reference
In-Depth Information
Then you use the canvas context to draw the sprite:
var ctx = powerupjs.Canvas2D._pixeldrawingCanvas.getContext('2d');
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.drawImage(this._image, 0, 0, w, h, 0, 0, w, h);
ctx.restore();
The canvas context has a method getImageData that retrieves the color data for each pixel and
stores it in an array. So, let's retrieve all the pixels currently displayed on the canvas:
var imageData = ctx.getImageData(0, 0, w, h);
The imageData variable now refers to a very large array of numbers. For each pixel, there are four
numbers in the array, each between 0 and 255. The first three numbers are the R (red), G (green),
and B (blue) values that determine the color of the pixel. The fourth number is the A (alpha) value that
determines the transparency of the pixel. An alpha value of 0 means the pixel is fully transparent,
and a value of 255 means the pixel is opaque. In the collision mask, you only need to store the alpha
values, because the color of objects that collide isn't important: only which pixels represent those
objects. So, you use a for instruction to iterate through the array and store each fourth value in the
collision-mask array, as follows:
for (var x = 3, l = w * h * 4; x < l; x += 4) {
this._collisionMask.push(imageData.data[x]);
}
When creating a SpriteSheet instance, the collision mask is calculated only when the user has set
the parameter createCollisionMask to true when calling the constructor. For example, you indicate
that you want precise collision detection for the player when the player sprites are loaded:
sprites.player_idle = loadSprite("player/spr_idle.png", true);
sprites.player_run = loadSprite("player/spr_run@13.png", true);
sprites.player_jump = loadSprite("player/spr_jump@14.png", true);
On the other hand, you don't need such precise information for the tiles, because those are more or
less rectangular anyway, so using a rectangular bounding box suffices:
sprites.wall = loadSprite("tiles/spr_wall.png");
sprites.wall_hot = loadSprite("tiles/spr_wall_hot.png");
sprites.wall_ice = loadSprite("tiles/spr_wall_ice.png");
sprites.platform = loadSprite("tiles/spr_platform.png");
sprites.platform_hot = loadSprite("tiles/spr_platform_hot.png");
sprites.platform_ice = loadSprite("tiles/spr_platform_ice.png");
In order to make it easier to access the collision mast, you add a getAlpha method to the
SpriteSheet class to access the collision mask while taking into account the currently selected
element in the sheet and whether the sprite is drawn mirrored. Here is the header of that method:
SpriteSheet.prototype.getAlpha = function (x, y, sheetIndex, mirror)
 
Search WWH ::




Custom Search