旋转Microsoft.XNA.Framework.Rectangle并根据该旋转创建一个矩形?

时间:2011-01-01 16:12:04

标签: c# xna

我一直试图这样做,但没有取得多大成功。我想做的就是旋转矩形,然后创建一个包含旋转点的新矩形。

任何人都有任何想法应该如何正确完成?

我的代码不起作用,但我不确定它到底出错的地方(这些数字让我觉得它确实有效),例如,如果我有一个具有以下值的矩形:

{X:865 Y:76 Width:22 Height:164}

结果是:

{X:1863 Y:1740 Width:164 Height:22}

旋转-1.57094443

我所做的就是抓住原始矩形的所有四个点并使用此功能旋转它们:

static public Vector2 RotateVectorAround(Vector2 anchor, Vector2 vector, float rotation)
        {
            Matrix mat = new Matrix();
            mat.Translation = new Vector3(vector.X - anchor.X, vector.Y - anchor.Y, 0);

            Matrix rot = new Matrix(); 
            rot = Matrix.CreateRotationZ(rotation);

            mat *= rot;

            mat.Translation += new Vector3(anchor.X, anchor.Y, 0);

            return new Vector2(mat.Translation.X, mat.Translation.Y);
        }

'anchor'是枢轴点(我不确定这个函数是否在数学上是合理的),然后我用这个确定旋转矩形的角:

Vector2 newTopLeft = new Vector2(  Math.Min(Math.Min(topleft.X, bottomRight.X), Math.Min(bottomleft.X, topright.X)),
                Math.Min(Math.Min(topleft.Y, bottomRight.Y), Math.Min(bottomleft.Y, topright.Y)));

            Vector2 newBottomRight = new Vector2(
                Math.Max(Math.Max(topleft.X, bottomRight.X), Math.Max(bottomleft.X, topright.X)),                
                Math.Max(Math.Max(topleft.Y, bottomRight.Y), Math.Max(bottomleft.Y, topright.Y) ));

1 个答案:

答案 0 :(得分:6)

您可以将矩形的点与旋转矩阵相乘。

因此,在旋转中给定点 P 将导致点 R

其中 a 是轮换

a = degrees * (PI/180)

Rx = Px * cos(a)  +  Py * -sin(a) 
Ry = Px * sin(a)  +  Py * cos(a) 

旋转一个点,您可以在旋转之前减去枢轴点,然后再次旋转后添加它们(因此旋转几乎在(0,0)左右

Px = Px - PivotX
Py = Py - PivotY

Rx = Px * cos(a)  +  Py * -sin(a) 
Ry = Px * sin(a)  +  Py * cos(a) 

Px = Rx + PivotX
Py = Ry + PivotY

我不会在这里使用第3个维度进行2d旋转

在XNA中的

就像(抱歉没有VStudio):

point -= pivot
point = Vector2.Transform(point, Matrix.CreateRotationZ(angle));
point += pivot
相关问题