Python/Pygame中的矩形旋转
嘿,我想把一个矩形绕着它的中心旋转,但每次我尝试旋转这个矩形时,它都会同时向上和向左移动。有没有人知道怎么解决这个问题?
def rotatePoint(self, angle, point, origin):
sinT = sin(radians(angle))
cosT = cos(radians(angle))
return (origin[0] + (cosT * (point[0] - origin[0]) - sinT * (point[1] - origin[1])),
origin[1] + (sinT * (point[0] - origin[0]) + cosT * (point[1] - origin[1])))
def rotateRect(self, degrees):
center = (self.collideRect.centerx, self.collideRect.centery)
self.collideRect.topleft = self.rotatePoint(degrees, self.collideRect.topleft, center)
self.collideRect.topright = self.rotatePoint(degrees, self.collideRect.topright, center)
self.collideRect.bottomleft = self.rotatePoint(degrees, self.collideRect.bottomleft, center)
self.collideRect.bottomright = self.rotatePoint(degrees, self.collideRect.bottomright, center)
2 个回答
0
也许这对你有帮助:
#load image
image1 = pygame.image.load(file)
#get width and height of unrotated image
width1,height1 = image1.get_size()
#rotate image
image2 = pygame.transform.rotate(image1, angle)
#get width,height of rotated image
width2,height2 = image2.get_size()
#blit rotated image (positon - difference of width or height /2)
display.blit(image2,[round(x - (width1 - width2)/2),round(y - (height1 - height2)/2)])
1
你的旋转代码看起来没问题,但你知道pygame的内部处理不支持旋转的矩形吗?
除非你自己写了代码来处理新的矩形角点,否则这段代码定义了一个新的矩形,这个矩形的边是和表面边平行的。也就是说,原来的矩形在旋转后可以放进这个新矩形里,而不是说新矩形和原来的矩形在倾斜角度下是一样大的。任何你在旋转后传给“self.collideRect”对象的Pygame函数,都会把这个矩形当作和表面对齐的,就好像它是用现在的角点创建的一样。
如果你的代码需要检查某些东西,或者甚至在旋转的矩形内绘制内容,你必须在旋转之前进行所有的计算,然后在显示你想要的内容时再进行坐标的旋转。也就是说,你需要使用一个全局的坐标变换,这个变换在渲染的最后一步应用。