旋转2D对象的函数?
旋转2D对象的函数?
首先,我们需要一个围绕原点旋转点的函数。
当我们将点(x,y)围绕原点旋转theta度时,我们得到以下坐标:
(x*cos(theta)-y*sin(theta), x*sin(theta)+y*cos(theta))
如果我们想围绕原点以外的点旋转它,我们只需要将其移动,使中心点成为原点。
现在,我们可以编写以下函数:
from math import sin, cos, radians def rotate_point(point, angle, center_point=(0, 0)): """Rotates a point around center_point(origin by default) Angle is in degrees. Rotation is counter-clockwise """ angle_rad = radians(angle % 360) # Shift the point so that center_point becomes the origin new_point = (point[0] - center_point[0], point[1] - center_point[1]) new_point = (new_point[0] * cos(angle_rad) - new_point[1] * sin(angle_rad), new_point[0] * sin(angle_rad) + new_point[1] * cos(angle_rad)) # Reverse the shifting we have done new_point = (new_point[0] + center_point[0], new_point[1] + center_point[1]) return new_point
一些输出:
print(rotate_point((1, 1), 90, (2, 1))) # This prints (2.0, 0.0) print(rotate_point((1, 1), -90, (2, 1))) # This prints (2.0, 2.0) print(rotate_point((2, 2), 45, (1, 1))) # This prints (1.0, 2.4142) which is equal to (1,1+sqrt(2))
现在,我们只需要使用我们之前的函数旋转多边形的每个角:
def rotate_polygon(polygon, angle, center_point=(0, 0)): """Rotates the given polygon which consists of corners represented as (x,y) around center_point (origin by default) Rotation is counter-clockwise Angle is in degrees """ rotated_polygon = [] for corner in polygon: rotated_corner = rotate_point(corner, angle, center_point) rotated_polygon.append(rotated_corner) return rotated_polygon
示例输出:
my_polygon = [(0, 0), (1, 0), (0, 1)] print(rotate_polygon(my_polygon, 90)) # This gives [(0.0, 0.0), (0.0, 1.0), (-1.0, 0.0)]
喜欢这个答案,非常有帮助!由于某种原因,对于大于360度的角度,它的效果不是很好,所以我在那之后添加了while counterangle > 0: counterangle -= 360
和while counterangle < 0: counterangle += 360
。这样,所有角度都变为正数并小于360。我还添加了counterangle = 360 - angle
,以便我可以使用顺时针角度。
你可能只需要在函数中使用counterangle % 360
作为旋转量。
是的,现在我已经更深入地研究了一年半,我意识到这一点。谢谢;)
很棒的答案-这对我所需的完美无缺!