2012-01-20 65 views
1

嘿,我正试图围绕它的中心旋转一个矩形,当我尝试旋转矩形时,它同时向上移动并向左移动。有没有人有任何想法如何解决这个问题?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) 

回答

1

旋转代码看起来是很好 - 但是,大家都知道,pygame中的内部不旋转的矩形工作,你呢?

除非你有一些代码是用新的矩形边角编写的,否则它会定义一个新的矩形,其边与边表面平行,其中原始矩形旋转时可以刻入,而不是一个与原始角度相同的矩形。任何在旋转后传递“self.collideRect”对象的Pygame函数都可以做到这一点:将矩形对齐到曲面,就好像它已经用它现在的角落创建了一样。

如果您的代码要求您检查事物,甚至在旋转的矩形内绘制,则必须执行与旋转之前相同的所有计算,并在显示内容时执行坐标旋转你要。也就是说,你使用全局坐标变换,这是在渲染的最后一步中应用的。

+1

所以你的意思是,如果我要检查,看是否有在矩形内的碰撞,我不得不做出的一个副本矩形,然后每次从副本旋转它?对不起,我只是很难理解这一点。 – mramazingguy

+1

对于任何未来碰到过这个问题的人......他说的是Pygame的引擎不理解旋转的矩形。除了常规的未旋转矩形之外,您无法对其进行碰撞检测。 – atomictom

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)])