Game Development Reference
In-Depth Information
As parameters, the method expects the x and y pixel coordinates, the sheet index, and whether the
sprite is mirrored. The first thing to do is check whether there is a collision mask associated with
this sprite sheet, because not all sprites have such a mask. If there is no collision mask, you simply
return the value 255 (fully opaque):
if (this._collisionMask === null)
return 255;
Then you calculate the column and row indices corresponding to the current sheet index, in the
same way you did in the draw method:
var columnIndex = sheetIndex % this._sheetColumns;
var rowIndex = Math.floor(sheetIndex / this._sheetColumns) % this._sheetRows;
You can then calculate the actual pixel coordinates in the image (or texture ), taking into account the
sprite element given by the sheet index. You calculate the x coordinate by multiplying the width of
one sheet element by the column index and adding the local x value:
var textureX = columnIndex * this.width + x;
However, if the sprite is mirrored, you use a slightly different calculation:
if (mirror)
textureX = (columnIndex + 1) * this.width - x - 1;
What happens here is that you start from the right side of the sprite element and then subtract x to
get the local x coordinate. For the y coordinate, mirroring doesn't have to be checked because you
only allow horizontal mirroring in the game engine:
var textureY = rowIndex * this.height + y;
Based on the x and y coordinates in the image, you now calculate the corresponding index in the
collision mask, as follows:
var arrayIndex = Math.floor(textureY * this._image.width + textureX);
Just to be sure, you check whether the index you calculated falls in the range of the array. If not, you
return 0 (fully transparent):
if (arrayIndex < 0 || arrayIndex >= this._collisionMask.length)
return 0;
This way, the getAlpha method also returns a logical result if you try to access nonexistent pixels.
Finally, you return the alpha value stored in the collision mask:
return this._collisionMask[arrayIndex];
 
Search WWH ::




Custom Search