在不降低帧率的情况下减慢 PyGame 精灵动画

Slowing down PyGame sprite animation without lowering frame rate

我正在尝试学习 pygame 精灵动画。我尝试按照教程进行操作,一切都很好。只有一个问题我想不通。

在下面的代码中,我正在尝试 运行 简单方块的精灵动画。 这是精灵: https://www.dropbox.com/s/xa39gb6m3k8085c/playersprites.png

我可以让它工作,但动画太快了。我希望它更平滑一点,以便可以看到褪色效果。我看到一些使用 clock.tick 的解决方案,但我猜这会减慢整个游戏的速度。

如何在保持 window 的正常帧率的同时让动画变慢?

下面是我的代码:

lightblue=(0,174,255)
import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
screen.fill(lightblue)
images=pygame.image.load('playersprites.png')
noi=16
current_image=0
while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                        pygame.quit()
                        quit()
        if(current_image>noi-1):
            current_image=0
        else:
            current_image+=1
        screen.blit(images,(50,100),(current_image*32,0,32,32))
        pygame.display.flip()

Clock.tick() 是正确的解决方案。

虽然您可能希望尽快 运行 游戏代码,但您不希望 动画 到 运行任意速度。动画总是"frames per second",这个值应该是稳定的;否则它会看起来很难看或令人困惑。一个好的值与您的显示器的刷新率(通常为 60 FPS)相同,以避免 tearing.

使用您在循环中添加的整数值并检查可整除性。有关更多信息,请参阅 here

你可以利用时间

所以你的精灵有 16 帧,假设它想要 运行 每秒 10 帧,而不管游戏的帧速率如何。

你可以按照

的方式做一些事情
import time
start_frame = time.time()
noi = 16
frames_per_second = 10

然后在你的循环中输入

current_image = int((time.time() - start_frame) * frames_per_second % noi)

time.time() 以秒为单位计数,后面有几个小数位。如果你遗漏 frames_per_second 则只需在 noi(大概是 "number of images")上使用模运算符,每次秒过去了,结果会加一,直到达到 16 和 return 到 0。

当您将 start_frame 与当前时间 (time.time() 相乘时,您强制 "seconds" 以 frames_per_second 倍的速度运行。

float 的结果强制转换为 int,将允许您将其用作索引。

现在如果游戏的帧率有波动,也没有关系,因为精灵的帧率与系统时钟有关。精灵仍应 运行 以尽可能接近所选择的帧速率进行渲染。