【问题标题】:Rotating an inner rectangle(or square) in c#在 C# 中旋转内部矩形(或正方形)
【发布时间】:2015-02-05 02:16:40
【问题描述】:

我正在尝试在另一个矩形内的一个矩形上应用一个转换......并且有相当多的困难。这是我试图实现的示例,旋转将始终以 90 度为增量:

我有外部和内部矩形的左下角 X/Y、宽度和高度......我正在尝试为转换后的内部矩形计算这些相同的值。

我的尝试可以在下面找到,我尝试围绕大矩形的中心旋转所有 4 个角,然后将它们重新组合成一个矩形。这可能不起作用,因为大矩形宽度/高度在旋转过程中会发生变化。有谁知道一个公式来完成这个?如果有人可以向我指出一些很棒的资源,那就太好了。

我的代码:

Vector2 center = new Vector2(largeRectWidth / 2.0f, largeRectHeight / 2.0f);

Rect innerRectRotated = RotateRectangleAroundPivot(innerRect, center, this.Rotation);

public static Rect RotateRectangleAroundPivot(Rect rect,
                                              Vector2 pivot,
                                              float rotation)
{
    Vector2 leftTop = new Vector2(rect.x, rect.y + rect.height);
    Vector2 rightTop = new Vector2(rect.x + rect.width, rect.y + rect.height);
    Vector2 leftBottom = new Vector2(rect.x, rect.y);
    Vector2 rightBottom = new Vector2(rect.x + rect.width, rect.y);

    leftTop = RotatePointAroundPivot(leftTop, pivot, rotation);
    rightTop = RotatePointAroundPivot(rightTop, pivot, rotation);
    leftBottom = RotatePointAroundPivot(leftBottom, pivot, rotation);
    rightBottom = RotatePointAroundPivot(rightBottom, pivot, rotation);

    Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
                              Vector2.Min(leftBottom, rightBottom));
    Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
                              Vector2.Max(leftBottom, rightBottom));

    return new Rect(min.x, min.y, (max.x - min.x), (max.y - min.y));
}

public static Vector2 RotatePointAroundPivot(Vector2 point, Vector2 pivot, float angle)
{
    angle = angle * Mathf.PI / 180.0f;
    return new Vector2((float)(Math.Cos(angle) * (point.x - pivot.x) - Math.Sin(angle) * (point.y - pivot.y) + pivot.x), (float)(Math.Sin(angle) * (point.x - pivot.x) + Math.Cos(angle) * (point.y - pivot.y) + pivot.y));
}

【问题讨论】:

    标签: c# math unity3d rectangles rect


    【解决方案1】:

    在 2D 中很好地进行 90 度旋转,您不需要任何三角函数

    • 改用这个:
    • 输入点 (x,y) 旋转 90 度,如下所示:
    • xx=y; yy=-x;
    • 另一个方向是:
    • xx=-y; yy=x;
    • 哪个公式是 CW 和 CCW 取决于您的坐标系
    • 展位围绕点 (0,0) 旋转点 90 度
    • 因此,如果您想旋转任何其他点,只需移动之前和之后的点...

    这样做:

    1. 将点平移到您的旋转中心

      • x-=x0; y-=y0;
    2. 向左或向右旋转

      • 例如:
      • aa=x; bb=y; x=-bb; y=+aa;
    3. 向后平移

      • x+=x0; y+=y0;
    4. 现在x,y 持有旋转点

    [注释]

    • 如果您希望旋转中心位于矩形的中间
    • 那么x0,y0 是平均点...
    • 所以如果矩形被定义为x1,y1,...,x4,y4
    • 然后x0=(x1+x2+x3+x4)/4.0;y0=(y1+y2+y3+y4)/4.0;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-04
      • 2017-04-18
      • 2017-10-21
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多