Python 旋转二维多边形而不更改其位置
我有这个密码:Python 旋转二维多边形而不更改其位置,python,polygons,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
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)
类矢量2D(对象):
定义初始化(self,x=0.0,y=0.0):
self.x,self.y=x,y
def旋转(自身、角度):
角度=数学弧度(角度)
sin=math.sin(角度)
cos=数学cos(角度)
x=自我。x
y=self.y
self.x=x*cos-y*sin
self.y=x*sin+y*cos
定义报告(自我):
返回“”。格式(self.x,self.y)
类多边形(对象):
定义初始值(自身,点):
self.points=[Vector2D(*点)表示点中点]
def旋转(自身、角度):
对于自我点中的点:
点。旋转(角度)
def中心(自我):
totalX=totalY=0.0
对于我,在self.points中:
totalX+=i.x
总y+=i.y
len_点=len(自点)
返回向量2D(总X/len_点,总Y/len_点)
问题是,当我旋转多边形时,它也会移动,而不仅仅是旋转
那么,如何在不改变多边形位置的情况下围绕其中心旋转多边形呢?您是围绕
0/0
旋转,而不是围绕其中心旋转。旋转前尝试移动多边形,使其中心位于0/0
。然后旋转它,最后将其向后移动
例如,如果在这种特殊情况下只需要移动顶点/多边形,则可能只需将旋转调整为:
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,0。这样,每个对象都可以在其自己的局部坐标系中旋转、缩放等。完成所有这些变换后,对象将变换到视图坐标系中的当前位置。这样,您只需要维护对象本身(未修改)和一组转换,这些转换的优先级取决于它们是本地的还是面向视图的。。。那是我的错。建议的代码实际上非常有效!