Search code examples
pythonpolygons

Rotate 2D polygon without changing its position


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?


Solution

  • 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