2

I've got this code:

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)

The problem is that when I rotate the polygon it also moves, not only rotates.

So how to rotate polygon around its center, without changing its position?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ivknv
  • 305
  • 1
  • 4
  • 14

1 Answers1

7

You're rotating around 0/0, not around its center. Try moving the polygon before rotating, such that its center is 0/0. Then rotate it, and finally move it back.

For instance, if you only need movement of vertices/polygons for this particular case, you could probably simply adjust rotate to be:

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
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
  • But now I have other problem: the polygon is being 'stretched'. Something weird is happening – ivknv Feb 11 '15 at 15:57
  • 1
    Another suggestion.. Generally, in graphics applications, you really want every object's center to be at 0,0. This way, each object can be rotated, scaled, etc. in its own local coordinate system. After all of these transformations are completed, the object is then transformed to its present location in the view's coordinate system. This way, you need only maintain the objects themselves (unmodified) and a set of transformations that are applied with a precedence based on whether they are local or view oriented. – David Hoelzer Feb 11 '15 at 16:06
  • Whoops... That was my bad. Suggested code actually works great! – ivknv Feb 11 '15 at 16:09