我有这样的代码:
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
。然后旋转,最后将其移回。
例如,如果在这种特殊情况下只需要移动顶点/多边形,则可以简单地将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