旋转2D多边形而不更改其位置

ivk*_*knv 2 python polygons

我有这个代码:

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)
Run Code Online (Sandbox Code Playgroud)

问题是,当我旋转多边形时,它也会移动,而不仅仅是旋转.

那么如何围绕中心旋转多边形而不改变它的位置呢?

Fre*_*abe 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
Run Code Online (Sandbox Code Playgroud)