如何从中心旋转图像而不是在pygame中的角落?

时间:2015-10-03 03:16:56

标签: python python-2.7 pygame

我正在创造一个游戏,我需要旋转船,我怎么能从中心而不是左上角旋转船?我正在使用python 2.7和Pygame 1.9。

以下是我必须旋转图像的代码。

shipImg = pygame.transform.rotate(shipImg,-90)

然而,这会从角落旋转图像。

1 个答案:

答案 0 :(得分:2)

旋转精灵,然后将新矩形的中心设置为旧矩形的中心。这样,当你完成时,新的中心具有相同的中心,使其看起来像是围绕中心旋转。

以下是pygame wiki的示例函数:

def rot_center(image, rect, angle):
    """rotate an image while keeping its center"""
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = rot_image.get_rect(center=rect.center)
    return rot_image,rot_rect

以下是您在示例中使用它的方法:

# Draw ship image centered around 100, 100
oldRect = shipImg.get_rect(center=(100,100)) 
screen.blit(shipImg, oldRect) 

# Now  rotate the ship and draw it with the new rect, 
# which will keep it centered around 100,100
shipImg, newRect = rot_center(shipImg,oldRect,-90)
screen.blit(shipImg, newRect)