Checking for Intersection Between Two Objects

After we have detected that we have a bounding box collision, we can simply loop through all of the pixels in each ImageData set, find the ones that match, and then check to see whether the alpha value for that pixel is 0. The problem with this approach is that it is slow and pretty much unusable for objects larger than a few pixels in width and height. Our 48×48 pixel images are each composed of 2,304 individual pixels. That is far too many to loop through on each frame tick, even for a single collision test. What we are going to do first is find where the two bounding boxes for our objects intersect and then check only those pixels.

Figure 4-20 shows an area of intersection where there would be a pixel-based collision.

The area where a pixel based collision will take place

Figure 4-20. The area where a pixel based collision will take place

To check the pixels in only the area of intersection rather than the entire set of pixels in each object, we need to first find this area of intersection. We will accomplish this by using the Math.min and Math.max Javascript functions on the current object positions and their associated widths and heights:

var xMin = Math.max( blueObject.x, redObject.x );
var yMin = Math.max( blueObject.y, redObject.y );
var xMax = Math.min( blueObject.x+blueObject.width, redObject.x+redObject.width );
var yMax = Math.min( blueObject.y+blueObject.height, redObject.y+redObject ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.