Game Development Reference
In-Depth Information
Fig. 27.2 Calculating the
overlap rectangle using the
minimal and maximal x and
y coordinates
The Intersection method takes two bounding boxes and returns another rectangle that
represents the overlap of the two boxes.
In order to calculate this overlap rectangle, we need to know what the minimal
and maximal x and y coordinates are of the rectangle (see Fig. 27.2 ).Usingafew
useful properties from the Rectangle class in combination with the Min and Max meth-
ods of the Math class, we can calculate these values quite easily:
int xmin = ( int )MathHelper.Max(rect1.Left, rect2.Left);
int xmax = ( int )MathHelper.Min(rect1.Right, rect2.Right);
int ymin = ( int )MathHelper.Max(rect1.Top, rect2.Top);
int ymax = ( int )MathHelper.Min(rect1.Bottom, rect2.Bottom);
Now we can calculate the position and size of the overlap rectangle, and return it
from the method:
xmin, ymax ymin);
return new Rectangle(xmin, ymin, xmax
Inside the CollidesWith method in SpriteGameObject , we store the overlap rectangle by
calling the Intersection method from the Collision class:
Rectangle b = Collision.Intersection(BoundingBox, obj.BoundingBox);
In order to check for collision within the overlap rectangle, we use a nested for -
instruction to walk over all the pixels in the rectangle:
for ( int x = 0; x < b.Width; x++)
for ( int y = 0; y < b.Height; y++)
checkifthepixelsatposition(x,y)arebothnottransparent
Inside the nested loop, we have to calculate what the local pixel coordinates are in
the current sprite, as well as the sprite that was passed as a parameter. Again, we
need to calculate these local coordinates using global positions, and we need to take
the origin into account:
Search WWH ::




Custom Search