Game Development Reference
In-Depth Information
For convenience, you also add a getAlpha method to SpriteGameObject that calls the getAlpha
method from SpriteSheet with the right parameters:
SpriteGameObject.prototype.getAlpha = function (x, y) {
return this.sprite.getAlpha(x, y, this._sheetIndex, this.mirror);
};
Note Not all browsers always allow you to access pixel color data. For example, Chrome
and Firefox don't allow this access if you open the HTML page as a local file on your
computer. Internet Explorer does allow this, so to test per-pixel collision detection you
can use that browser or put the files on a server in order to use either of the browsers. In
the TickTick2 example, I commented out the collisionMask parameter in TickTick.js so
the game runs on all browsers, but of course the game doesn't perform per-pixel collision
detection in this case.
Calculating the Overlap Rectangle
The collidesWith method in SpriteGameObject handles the two steps of collision detection: first
checking whether the bounding boxes intersect and then performing per-pixel collision detection
in the overlap rectangle. The first step in this method is to determine whether you need to do any
collision detection at all. If either of the two objects is invisible, or if their bounding boxes don't
intersect, you return from the method:
if (!this.visible || !obj.visible ||
!this.boundingBox.intersects(obj.boundingBox))
return false;
The next step is calculating the overlapping part of the two bounding boxes. Because this is a
useful thing to calculate when dealing with collision detection in general, you add a method called
intersection to the Rectangle class that returns a rectangle representing the overlap between the
rectangle (bounding box) passed as a parameter and the rectangle object you call the method on ( this ).
To calculate this overlap rectangle, you need to know the minimum and maximum x and y
coordinates for the rectangle (see Figure 26-3 ). Using a few useful properties from the Rectangle
class in combination with the min and max methods of the Math object, you can calculate these
values quite easily:
var xmin = Math.max(this.left, rect.left);
var xmax = Math.min(this.right, rect.right);
var ymin = Math.max(this.top, rect.top);
var ymax = Math.min(this.bottom, rect.bottom);
 
Search WWH ::




Custom Search