HTML and CSS Reference
In-Depth Information
Checking for Intersection Between Two Objects
Afterwehavedetected thatwehaveaboundingboxcollision,wecansimplyloopthroughall
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 im-
ages 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.
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 associ-
ated 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 . height
Based on the locations of the two objects and the width (or height, depending on the axis),
these will give us four values needed to define the area in intersection.
Search WWH ::

Custom Search