我有这段代码:
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 :(得分:7)
你在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