【问题标题】:Rotating a Microsoft.XNA.Framework.Rectangle and creating a rectangle based on that rotation?旋转 Microsoft.XNA.Framework.Rectangle 并基于该旋转创建一个矩形?
【发布时间】:2011-01-02 01:06:51
【问题描述】:

我已经尝试这样做了一段时间,但没有取得太大的成功。我要做的就是旋转矩形,然后创建一个包含旋转点的新矩形。

有人知道应该如何正确完成吗?

我的代码不起作用,但我不确定它到底哪里出了问题(这些数字让我认为它确实有效),例如,如果我有一个具有以下值的矩形:

{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) ));

【问题讨论】:

    标签: c# xna


    【解决方案1】:

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

    所以在旋转中给定点 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多