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

twe*_*ypi 4 c# xna

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

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

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

{X:865 Y:76 Width:22 Height:164}
Run Code Online (Sandbox Code Playgroud)

结果是:

{X:1863 Y:1740 Width:164 Height:22}
Run Code Online (Sandbox Code Playgroud)

旋转的地方-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);
        }
Run Code Online (Sandbox Code Playgroud)

'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) ));
Run Code Online (Sandbox Code Playgroud)

Cas*_*jne 6

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

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

其中a是旋转

a = degrees * (PI/180)

Rx = Px * cos(a)  +  Py * -sin(a) 
Ry = Px * sin(a)  +  Py * cos(a) 
Run Code Online (Sandbox Code Playgroud)

旋转一个点,您可以在旋转之前减去枢轴点,并在旋转之后添加它们(因此旋转几乎在(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
Run Code Online (Sandbox Code Playgroud)

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

在XNA中就像是(抱歉没有VStudio):

point -= pivot
point = Vector2.Transform(point, Matrix.CreateRotationZ(angle));
point += pivot
Run Code Online (Sandbox Code Playgroud)