2015-02-11 77 views
2

我有了这个代码旋转2D多边形:不改变其位置

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) 

的问题是,当我旋转它也移动多边形,不仅转动。

那么如何在其中心旋转多边形而不改变其位置?

回答

6

你正在围绕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 
+0

但是现在我有其他的问题:多边形被“拉长” 。奇怪的事情发生 – ivknv 2015-02-11 15:57:01

+0

另一个建议..一般来说,在图形应用程序中,你真的希望每个对象的中心在0,0。这样,每个对象都可以在自己的本地坐标系中旋转,缩放等。在完成所有这些转换之后,对象将转换为视图坐标系中的当前位置。这样,您只需要维护对象本身(未修改)和一组根据其是本地还是视图导向应用优先级的变换。 – 2015-02-11 16:06:52

+0

哎呦......那是我的不好。建议的代码实际上很棒! – ivknv 2015-02-11 16:09:12