【问题标题】:XNA/Monogame Creating rectangle around texture regardless of rotation?XNA/Monogame 在纹理周围创建矩形而不考虑旋转?
【发布时间】:2017-03-22 08:07:01
【问题描述】:

我知道Rectangle 是轴对齐的,这很好,我只是不知道如何创建一个矩形,所以它总是包含整个精灵,而不管旋转。我一直在到处寻找答案,但在任何地方都找不到一个直接的答案。

例如:

假设原点是纹理的中间,我该怎么做呢?

编辑

稍微摆弄一下,我已经做到了这一点:

public Rectangle BoundingBox
{
    get
    {

        var cos = Math.Cos(SpriteAngle);
        var sin = Math.Cos(SpriteAngle);

        var t1_opp = Width * cos;
        var t1_adj = Math.Sqrt(Math.Pow(Width, 2) - Math.Pow(t1_opp, 2));

        var t2_opp = Height * sin;
        var t2_adj = Math.Sqrt(Math.Pow(Height, 2) - Math.Pow(t2_opp, 2));

        int w = Math.Abs((int)(t1_opp + t2_opp));
        int h = Math.Abs((int)(t1_adj + t2_adj));

        int x = Math.Abs((int)(Position.X) - (w / 2));
        int y = Math.Abs((int)(Position.Y) - (h / 2));

        return new Rectangle(x, y, w, h);

    }
}

【问题讨论】:

    标签: rotation xna trigonometry monogame rectangles


    【解决方案1】:

    (在我的脑海中这样做......但原则应该有效)

    创建一个矩阵以围绕矩形的中心旋转 - 即 -(x+width/2), -(y+height/2) 然后旋转角度 然后是 (x+width/2), (y+height/2) 的翻译

    使用Vector2.Transform对原矩形的每个角进行变换

    然后用 x = min(p1.x, p2.x, p3.x, p4.x) 宽度 = max(p1.x, p2.x, p3.x, p4.x) - x

    y 类似

    【讨论】:

      【解决方案2】:

      抱歉,来得太晚了,但我前一阵子想通了,忘记发布答案了。

      public virtual Rectangle BoundingBox
      {
          get
          {
              int x, y, w, h;
              if (Angle != 0)
              {
                  var cos = Math.Abs(Math.Cos(Angle));
                  var sin = Math.Abs(Math.Sin(Angle));
                  var t1_opp = Width * cos;
                  var t1_adj = Math.Sqrt(Math.Pow(Width, 2) - Math.Pow(t1_opp, 2));
                  var t2_opp = Height * sin;
                  var t2_adj = Math.Sqrt(Math.Pow(Height, 2) - Math.Pow(t2_opp, 2));
      
                  w = (int)(t1_opp + t2_opp);
                  h = (int)(t1_adj + t2_adj);
                  x = (int)(Position.X - (w / 2));
                  y = (int)(Position.Y - (h / 2));
              }
              else
              {
                  x = (int)Position.X;
                  y = (int)Position.Y;
                  w = Width;
                  h = Height;
              }
              return new Rectangle(x, y, w, h);
          }
      }
      

      就是这里了。在我的编辑工作中,我不小心在 sin 变量中添加了 Math.Cos,这没有帮助。

      所以这只是基本的三角函数。如果纹理角度不为零,则计算由宽度和高度形成的两个三角形的边,并将边用作宽度和高度的值,然后将矩形围绕纹理居中。如果这有意义的话。

      这是一张帮助解释的图片:

      这是最终结果的 gif:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        相关资源
        最近更新 更多