Game Development Reference
In-Depth Information
if
(A.Intersects(B))
performper-pixelcollisiondetectionhere
27.7 Retrieving Bounding Boxes
In order to handle collision efficiently in our game, we are going to extend the
SpriteGameObject
class with a property
BoundingBox
that returns the bounding box of
the sprite:
public override
Rectangle BoundingBox
{
get
{
−
int
left = (
int
)(GlobalPosition.X
origin.X);
int
top = (
int
)(GlobalPosition.Y
origin.Y);
return new
Rectangle(left, top, Width, Height);
−
}
}
As you can see, we take into account the origin of the sprite in order to calculate the
correct position of the box. Also, note that the bounding box position is expressed
using
global positions
. When doing collision detection, we want to know where the
objects are in the world, we do not care about their local positions in some hierarchy
of game objects.
27.8 Per-pixel Collision Detection
Next to the
BoundingBox
property, we have added a method
CollidesWith
to the
SpriteGameObject
class that deals with the collision detection. Next to checking if
the bounding boxes intersect, this method performs a per-pixel collision detection.
The first step in this method is to determine if we need to do any collision detec-
tion at all. If either of the two objects is invisible, or if their bounding boxes do not
intersect, we return from the method:
if
(!
this
.Visible || !obj.Visible || !BoundingBox.Intersects(obj.BoundingBox))
return false
;
The next step is calculating the overlapping part of the two bounding boxes. Since
this is a useful thing to calculate when dealing with collision detection in general,
we are going to create a new class
Collision
that contains a number of static meth-
ods that are useful for collision detection, very similar to how
MathHelper
functions.