旋转二维多边形而不改变其位置
Rotate 2D polygon without changing its position
我有这个代码:
class Vector2D(object):
def __init__(self, x=0.0, y=0.0):
self.x, self.y = x, y
def rotate(self, angle):
angle = math.radians(angle)
sin = math.sin(angle)
cos = math.cos(angle)
x = self.x
y = self.y
self.x = x * cos - y * sin
self.y = x * sin + y * cos
def __repr__(self):
return '<Vector2D x={0}, y={1}>'.format(self.x, self.y)
class Polygon(object):
def __init__(self, points):
self.points = [Vector2D(*point) for point in points]
def rotate(self, angle):
for point in self.points:
point.rotate(angle)
def center(self):
totalX = totalY = 0.0
for i in self.points:
totalX += i.x
totalY += i.y
len_points = len(self.points)
return Vector2D(totalX / len_points, totalY / len_points)
问题是当我旋转多边形时它也会移动,而不仅仅是旋转。
那么如何在不改变其位置的情况下围绕其中心旋转多边形?
您正在围绕 0/0
旋转,而不是围绕其中心旋转。尝试在旋转之前移动多边形,使其中心为 0/0
。然后旋转,最后移回。
例如,如果您只需要针对此特定情况移动 vertices/polygons,您可能只需将 rotate
调整为:
def rotate(self, angle):
center = self.center()
for point in self.points:
point.x -= center.x
point.y -= center.y
point.rotate(angle)
point.x += center.x
point.y += center.y
我有这个代码:
class Vector2D(object):
def __init__(self, x=0.0, y=0.0):
self.x, self.y = x, y
def rotate(self, angle):
angle = math.radians(angle)
sin = math.sin(angle)
cos = math.cos(angle)
x = self.x
y = self.y
self.x = x * cos - y * sin
self.y = x * sin + y * cos
def __repr__(self):
return '<Vector2D x={0}, y={1}>'.format(self.x, self.y)
class Polygon(object):
def __init__(self, points):
self.points = [Vector2D(*point) for point in points]
def rotate(self, angle):
for point in self.points:
point.rotate(angle)
def center(self):
totalX = totalY = 0.0
for i in self.points:
totalX += i.x
totalY += i.y
len_points = len(self.points)
return Vector2D(totalX / len_points, totalY / len_points)
问题是当我旋转多边形时它也会移动,而不仅仅是旋转。
那么如何在不改变其位置的情况下围绕其中心旋转多边形?
您正在围绕 0/0
旋转,而不是围绕其中心旋转。尝试在旋转之前移动多边形,使其中心为 0/0
。然后旋转,最后移回。
例如,如果您只需要针对此特定情况移动 vertices/polygons,您可能只需将 rotate
调整为:
def rotate(self, angle):
center = self.center()
for point in self.points:
point.x -= center.x
point.y -= center.y
point.rotate(angle)
point.x += center.x
point.y += center.y