给定其中心点和旋转,查找旋转矩形的角

Chr*_*sen 3 math trigonometry

如果我知道矩形的中心点(在全局坐标空间中)、宽度和高度以及围绕该中心点的旋转,有人能给我一个算法来找到矩形的所有四个角的位置吗?

澄清编辑:我所指的宽度和高度是矩形边长。

MBo*_*MBo 8

右上角具有相对于中心的 w/2、h/2 坐标。旋转后其绝对坐标为

 x = cx + w/2 * Cos(Phi) - h/2 * Sin(Phi)
 y = cy + w/2 * Sin(Phi) + h/2 * Cos(Phi)
Run Code Online (Sandbox Code Playgroud)


小智 8

每个顶点的坐标:

 Center point = (center.x, center.y)
 Angle        = angle
 Height       = height
 Width        = width      



TOP RIGHT VERTEX:
Top_Right.x = center.x + ((width / 2) * cos(angle)) - ((height / 2) * sin(angle))
Top_Right.y = center.y + ((width / 2) * sin(angle)) + ((height / 2) * cos(angle))



TOP LEFT VERTEX:
Top_Left.x = center.x - ((width / 2) * cos(angle)) - ((height / 2) * sin(angle))
Top_Left.y = center.y - ((width / 2) * sin(angle)) + ((height / 2) * cos(angle))



BOTTOM LEFT VERTEX:
Bot_Left.x = center.x - ((width / 2) * cos(angle)) + ((height / 2) * sin(angle))
Bot_Left.y = center.y - ((width / 2) * sin(angle)) - ((height / 2) * cos(angle))



BOTTOM RIGHT VERTEX:
Bot_Right.x = center.x + ((width / 2) * cos(angle)) + ((height / 2) * sin(angle))
Bot_Right.y = center.y + ((width / 2) * sin(angle)) - ((height / 2) * cos(angle))
Run Code Online (Sandbox Code Playgroud)

该算法是这 3 个步骤的压缩版本:

第 1 步:将矩形以原点为中心

步骤 2:将旋转矩阵应用到每个顶点

步骤 3:通过将中心点添加到每个坐标,将旋转的矩形移动到正确的位置

此处更深入地解释了这一点https://math.stackexchange.com/questions/126967/rotating-a-rectangle-via-a-rotation-matrix


小智 5

如果您需要所有的角,创建从矩形中心到其两侧的两个垂直向量可能会更快,然后将这些向量添加到/从矩形中心减去以形成点.

这可能会更快,因为您不需要重复调​​用 sin() 和 cos() 函数(每个函数只调用一次)。

假设我们有一个 Vector 库(用于更清晰的代码 - 仅有助于向量运算),这里是 Python 中的代码:

def get_corners_from_rectangle(center: Vector, angle: float, dimensions: Vector):
   # create the (normalized) perpendicular vectors
   v1 = Vector(cos(angle), sin(angle))
   v2 = Vector(-v1[1], v1[0])  # rotate by 90

   # scale them appropriately by the dimensions
   v1 *= dimensions[0] / 2
   v2 *= dimensions[1] / 2

   # return the corners by moving the center of the rectangle by the vectors
   return [
      center + v1 + v2,
      center - v1 + v2,
      center - v1 - v2,
      center + v1 - v2,
   ]
Run Code Online (Sandbox Code Playgroud)