Reputation: 4708
I've found no way of creating a 2D collision AABB on google, and I was wondering how the maths of it work. I was thinking that I could use some kind of matrix transforms to achieve it but that idea failed epically. So basically, I want to know of any resource that can help me create an Angle-Aligned Bounding Box and check if a point intersects it, or an explanation of the maths and logic of it.
Edit: I don't know if I made it clear, but I need to test collisions with them. Just to make that crystal clear.
Upvotes: 1
Views: 1080
Reputation: 11273
An intersection check between two Rectangles does not allow you to check against a rotated rectangle. The as the simple intersects function will not work. Your idea of calculating a Rectangle that encompasses your "actual" rotated Rectangle, and then checking for collisions on the Bounding Rectangles instead.
Here is some code that will return a Rectangle based on another Rectangle and a Rotation Matrix transformation:
public static Rectangle CalculateBoundingRectangle(Rectangle rectangle, Matrix transform)
{
// Get all four corners in local space
Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);
// Transform all four corners into work space
Vector2.Transform(ref leftTop, ref transform, out leftTop);
Vector2.Transform(ref rightTop, ref transform, out rightTop);
Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
Vector2.Transform(ref rightBottom, ref transform, out rightBottom);
// Find the minimum and maximum extents of the rectangle in world space
Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
Vector2.Min(leftBottom, rightBottom));
Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
Vector2.Max(leftBottom, rightBottom));
// Return that as a rectangle
return new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y));
}
Of course, this type of collision detection is fast, but not accurate. Your Bounding rectangle will not be a 1:1 representation of your shape. If you need more accuracy, you could then use a per-pixel collision check after checking with AABB.
This answer might also be of interest to you, particularly the answer on SAT.
Upvotes: 1