使用多图制作Pygame动画时循环切换出现闪烁问题
Pygame动画循环重置时闪烁问题
运行Pygame代码时,动画整体流畅,但当temp变量达到图片列表长度并重置为0时,画面会出现闪烁。已将图片制作成GIF测试,确认图片本身无帧序列问题,GIF播放流畅。
原代码:
import pygame,os pygame.init() window=pygame.display.set_mode((600,600)) clock=pygame.time.Clock() run=[] for image in os.listdir("run"): run.append( pygame.transform.scale( pygame.image.load("run/" + image), (40, 40), ).convert_alpha() ) temp=0 diff=0.2 index=0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() temp+=diff if temp>=len(run): temp=0 index=int(temp) print(index) window.fill("white") window.blit(run[index],(300,300)) pygame.display.flip() clock.tick(60)
问题原因
当前逻辑中,当temp达到图片列表长度时直接重置为0,会导致帧索引从len(run)-1突然跳转到0,出现帧序列的硬跳转,视觉上表现为闪烁。而GIF的循环是帧序列的平滑过渡,不会有这种突兀的跳转。
解决方案
用取模运算替代硬重置逻辑,让temp始终在合理范围内循环,避免索引跳变:
修改后的代码:
import pygame,os pygame.init() window=pygame.display.set_mode((600,600)) clock=pygame.time.Clock() run=[] for image in os.listdir("run"): run.append( pygame.transform.scale( pygame.image.load("run/" + image), (40, 40), ).convert_alpha() ) temp=0 diff=0.2 index=0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() temp+=diff # 用取模运算替代硬重置 temp = temp % len(run) index=int(temp) print(index) window.fill("white") window.blit(run[index],(300,300)) pygame.display.flip() clock.tick(60)
说明
取模运算会让temp在超过len(run)时,自动减去整数倍的列表长度,回到0到len(run)之间的范围。比如列表长度为10,当temp累加至10.2时,取模后得到0.2,索引仍为0,但前一帧temp为9.8时索引是9,实现了帧序列的平滑过渡,不会出现闪烁。
内容的提问来源于stack exchange,提问作者suyog
相关产品推荐
相关产品推荐

