Game Development Reference
In-Depth Information
Let's say you want to know whether rectangle A collides with rectangle B. In that case, you have to
check for the following conditions:
A.left
(A's smallest
x
-value) <=
B.right
(B's greatest
x
-value)
A.right
(A's greatest
x
-value) >=
B.left
(B's smallest
x
-value)
A.top
(A's smallest
y
-value) <=
B.bottom
(B's greatest
y
-value)
A.bottom
(A's greatest
y
-value) >=
B.top
(B's smallest
y
-value)
If all these conditions are met, then rectangles A and B have collided. Why these particular conditions?
Let's look at the first condition to see what happens if it isn't true. Suppose
A.left > B.right
instead.
In that case, rectangle A lies completely to the right of rectangle B, so they can't collide. If the
second condition isn't true (in other words,
A.right < B.left
), then rectangle A lies completely to
the left of B, which means they don't collide either. Check the other two conditions for yourself as
well. In summary, these conditions say that if rectangle A lies neither completely to the left, right, top,
or bottom of B, then the two rectangles collide.
In JavaScript, writing the code for checking collisions between rectangles is easy. If you look at the
Rectangle
class, you can see a method
intersects
that does this work for you:
Rectangle.prototype.intersects = function (rect) {
return (this.left <= rect.right && this.right >= rect.left &&
this.top <= rect.bottom && this.bottom >= rect.top);
};
Retrieving Bounding Boxes
To handle collisions efficiently in your game, the
SpriteGameObject
class has a property
boundingBox
that returns the bounding box of the sprite:
Object.defineProperty(SpriteGameObject.prototype, "boundingBox",
{
get: function () {
var leftTop = this.worldPosition.subtractFrom((this.origin));
return new powerupjs.Rectangle(leftTop.x, leftTop.y, this.width, this.height);
}
});
As you can see, it takes into account the sprite's origin in order to calculate the correct position of
the box. Also note that the bounding box's position is expressed using
world positions
. When doing
collision detection, you want to know where the objects are in the world—you don't care about their
local positions in a hierarchy of game objects.
Per-Pixel Collision Detection
In addition to the
boundingBox
property, you add a method
collidesWith
in the
SpriteGameObject
class that deals with collision detection. However, only checking whether bounding boxes overlap
is often not enough. Figure
26-2
shows an example of two sprites whose bounding boxes overlap,
Search WWH ::
Custom Search