So in my most recent 2D game I draw objects like so.
_spriteBatch.Draw(_sprite, Center(), null, Color.White, _rotation, new Vector2(_sprite.Width / 2, _sprite.Height / 2), _scale, SpriteEffects.None, 0);
My bounding boxes are generated using a two step algorithm where I make the transform matrix, then apply it to a Rectangle of the sprite's height and width.
public Rectangle BoundingBoxTransformed
{
get
{
//Center and rotate our Rectangle
Matrix m = Matrix.CreateScale(_scale) *
Matrix.CreateTranslation(new Vector3(new Vector2((float)-BoundingBox.Width / 2, (float)-BoundingBox.Height / 2), 0.0f)) *
Matrix.CreateRotationZ(_rotation) *
//Move our rectangle toward the player, then recenter it by undoing the original translation (now that it's already rotated)
Matrix.CreateTranslation(new Vector3(_location, 0.0f)) * Matrix.CreateTranslation(new Vector3((float)BoundingBox.Width / 2, (float)BoundingBox.Height / 2, 0.0f));
return CalculateBoundingRectangle(new Rectangle(0, 0, _sprite.Width, _sprite.Height), m);
}
}
This is how I've been finding the new sizes for the scaled bounding boxes.
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)); }
I thought that I had the transformations all figured out, but when I run the game, I can see that my bounding boxes do not match up with my sprites.
So what is it that's going on here? Are my transformations out of order? Quick edit: The purple boxes are the original bounding boxes, which are used to determine the height and width of the red (transformed, i.e. scaled and rotated) bounding boxes.
_rotation
? You should confirm it with a break point while debugging. \$\endgroup\$