2D BoundingRectangle rotation in XNA 4.0

2019-08-07 19:52发布

I'm having trouble working out what I need to do in order to have a 2D BoundingRectangle for a sprite object in my game rotate and update position depending on which way the user wants the sprite to travel.

I draw out the sprite with it's rotation and scale values like so:

spriteBatch.Draw(texture, position, null, Color.White, rotation, origin, scale, SpriteEffects.None, 1f);

My current setup for getting the BoundingRectangle is:

public Rectangle BoundingRectangle
{
    get { return new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height); }
}

The above is very basic and obviously won't rotate with the sprite. I've read a few QA posts and tried various things but none of them seem to achieve what I'm after or create very odd behaviours.

I'd be grateful for some suggestions on what I need to do.

1条回答
看我几分像从前
2楼-- · 2019-08-07 20:02

The Rectangle class doesn't contain rotation information, so you need some structure to contain that.

A good choice would be to return a list of four points, which are based on the rectangle you are now returning and the rotation applied to it.

You can apply apply a rotation on a set of points using the Matrix class like so:

var m = Matrix.CreateRotationZ(angle);
Vector3 rotatedVector = Vector3.Transform(vector, m);

If you want to rotate around a certain point, lets say the center of your sprite, a translation should also be done:

var rotation = Matrix.CreateRotationZ(angle);
var translateTo = Matrix.CreateTranslation(vector);
var translateBack = Matrix.CreateTranslation(-vector);
var comnbined = translateTo * rotation * translateBack;
Vector3 rotatedVector = Vector3.Transform(vectorToRotate, combined);

Be sure to check out all the other transformations that can be done with a matrix, matrices are core elements in game/graphics development.

查看更多
登录 后发表回答