2D BoundingRectangle rotation in XNA 4.0

梦想与她 提交于 2019-12-11 04:38:11

问题


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:


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.



来源:https://stackoverflow.com/questions/12552490/2d-boundingrectangle-rotation-in-xna-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!