Game Development Reference
In-Depth Information
but the images aren't actually colliding. This can happen because parts of the sprites that you draw
can be transparent. As a result, if you want to do precise collision detection, you need to look at the
pixel level if there is a collision. A collision at the pixel level happens only if at a given position in the
rectangle where sprites overlap, both sprites have a non-transparent pixel.
Figure 26-2. Example of two sprites that don't collide but whose bounding boxes overlap
Accessing Pixel Color Data in Images
To do per-pixel collision detection, you need access to an image's pixel color data. This isn't hard to
do in HTML/JavaScript, but before you see how, you need to know that per-pixel collision detection
is an expensive operation (you see why later). If you do it between each sprite in the game world,
you run the risk of your game no longer being playable on older mobile devices or tablets. So, do
per-pixel collision detection only when it's really necessary.
Because per-pixel collision detection is expensive, it makes sense to design the code in such a way
that it's easy to switch it off for certain sprites. To do this, you maintain a Boolean variable in the
SpriteSheet class that indicates whether per-pixel collision detection should be done for that sprite.
Because retrieving pixel color data is expensive, you retrieve all that data when the sprite is loaded
and store it in an array called a collision mask . Why is retrieving pixel color data expensive? Because
in order to retrieve that data, you need to first draw the sprite and then retrieve to color data from
the canvas. You don't want to draw these sprites on the main canvas that the player can see, so you
define another canvas just for this purpose in the Canvas2D class:
this._pixeldrawingCanvas = document.createElement('canvas');
You add a method called createPixelCollisionMask to the SpriteSheet class in which you draw
the sprite on the pixel drawing canvas and then extract the pixel color data from that canvas. You
initialize the array that will contain the collision mask, and you make sure the pixel drawing canvas is
the right size:
this._collisionMask = [];
var w = this._image.width;
var h = this._image.height;
powerupjs.Canvas2D._pixeldrawingCanvas.width = w;
powerupjs.Canvas2D._pixeldrawingCanvas.height = h;
 
Search WWH ::




Custom Search