pygame-旋转精灵并同时跟随路径

时间:2019-05-24 18:16:32

标签: python animation pygame rotation

我正在尝试为抛出的球设置动画,并且我希望它同时旋转一条光滑,抛物线的轨迹。但是,我似乎无法与pygame.transform.rotate()合作。

这是我到目前为止尝试过的:

import pygame
screen = pygame.display.set_mode((500, 500))
timer = pygame.time.Clock()
ball = pygame.sprite.Sprite()
ball.image = pygame.image.load("throwball.png")
ball.image = pygame.transform.scale(ball.image, (48,48))
ball.rect = ball.image.get_rect(topleft = (50,50))
ball.orig_image = ball.image
rotaterect = ball.rect

for i in range(60):
    #pygame.draw.rect(screen, Color(255,255,255), ball.rect)
    ball.image = pygame.transform.rotate(ball.orig_image, i*20)
    rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
    ball.rect.center = rotaterect.center
    screen.blit(ball.image, ball.rect)
    pygame.display.update()
    timer.tick(60)
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
while 1:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

每当我运行代码时,球都会以不规则的模式运动。我进行了第二次矫正,试图将位置保持在控制之下,但是球最终形成了这样的路径:this

显然,每个框架的位置都有问题,但是我不确定为什么任何一个框架都不合适,因为它们的位置是由它们的中心点决定的。

这是球的图像:

enter image description here

它是16x16(正方形),所以我对为什么图像未遵循干净路径感到震惊。

1 个答案:

答案 0 :(得分:1)

请注意,旋转的图像尺寸会有所不同。参见How do I rotate an image around its center using Pygame?

获取旋转图像的矩形,并通过辅助矩形rotaterect的中心设置矩形的中心。这导致图像围绕中心对称对齐。
您错过了将ball.rect更新为旋转图像的实际大小的操作:

ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center

示例:

for i in range(60):
    ball.image = pygame.transform.rotate(ball.orig_image, i*20)
    ball.rect = ball.image.get_rect()
    rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
    ball.rect.center = rotaterect.center
    screen.blit(ball.image, ball.rect)
    pygame.display.update()
相关问题