Skip to main content
3 of 3
added 25 characters in body
David Gouveia
  • 24.9k
  • 5
  • 87
  • 125

I always try to solve these geometrical problems using transformations instead of trigonometry, because at least for me it's easier to visualize. Here's how I do it on my application in XNA.

Let's say I have a sprite that's been translated, rotated and scaled arbitrarily and I want to fit an AABB to it. I only need to know two things about this sprite:

  • The world matrix containing all three transformations combined
  • The sprite's untransformed extents (i.e. it's original width and height)

(BTW, these two bits of information combined are also all you need in order to represent an OBB)

Knowing that, I proceed to calculate an AABB like this:

// Calculate the position of the four corners in world space by applying
// The world matrix to the four corners in object space (0, 0, width, height)
Vector2 tl = Vector2.Transform(Vector2.Zero, matrix);
Vector2 tr = Vector2.Transform(new Vector2(extents.x, 0), matrix);
Vector2 bl = Vector2.Transform(new Vector2(0, extents.y), matrix);
Vector2 br = Vector2.Transform(extents, matrix);

// Find the minimum and maximum "corners" based on the ones above
float minX = Min(tl.X, Min(tr.X, Min(bl.X, br.X)));
float maxX = Max(tl.X, Max(tr.X, Max(bl.X, br.X)));
float minY = Min(tl.Y, Min(tr.Y, Min(bl.Y, br.Y)));
float maxY = Max(tl.Y, Max(tr.Y, Max(bl.Y, br.Y)));
Vector2 min = new Vector2(minX, minY);
Vector2 max = new Vector2(maxX, maxY);

// And create the AABB
RectangleF aabb = new RectangleF(min, max - min);

Maybe it's longer but at least I understand every step of the process this way.

David Gouveia
  • 24.9k
  • 5
  • 87
  • 125