Pygame同时播放多个动画失效问题求助
问题分析
你的代码核心问题是全局变量time被两个动画共享。每次调用animation函数处理第一个火炬(torchA)时,只要满足时间条件就会重置全局time值,导致处理第二个火炬(torchB)时,pygame.time.get_ticks() - time的差值永远小于延迟时间(100ms),第二个火炬的计数器永远无法更新,动画自然无法运行。
解决方案
方案1:为每个动画单独维护时间变量
不用类,仅给每个动画单独保存上次更新的时间,修改animation函数使其接收并返回该时间即可:
import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode((480, 480)) clock=pygame.time.Clock() torchAImageList=[pygame.transform.scale(pygame.image.load(f"torchA{i+1}.png"),(48,96)) for i in range(4)] torchACount=0 torchADelay=100 torchALastTime=pygame.time.get_ticks() # 单独维护torchA的上次更新时间 torchBImageList=[pygame.transform.scale(pygame.image.load(f"torchB{i+1}.png"),(48,96)) for i in range(4)] torchBCount=0 torchBDelay=100 torchBLastTime=pygame.time.get_ticks() # 单独维护torchB的上次更新时间 def animation(delay, animationNumber, limitOfAnimation, last_time): current_time = pygame.time.get_ticks() if current_time - last_time > delay: animationNumber += 1 if animationNumber == limitOfAnimation: animationNumber = 0 last_time = current_time return animationNumber, last_time while True: for ev in pygame.event.get(): if ev.type == QUIT: pygame.quit() exit() # 防止退出后执行后续代码 clock.tick(60) screen.fill((0, 0, 0)) screen.blit(torchAImageList[torchACount],(100,100)) torchACount, torchALastTime = animation(torchADelay, torchACount, 4, torchALastTime) screen.blit(torchBImageList[torchBCount],(300,100)) torchBCount, torchBLastTime = animation(torchBDelay, torchBCount, 4, torchBLastTime) pygame.display.flip()
方案2:用类封装动画(更推荐,扩展性强)
当需要管理多个动画对象时,用类封装每个动画的状态(计数器、延迟、上次更新时间、帧列表)会更清晰,后续添加新动画也更方便:
import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode((480, 480)) clock=pygame.time.Clock() class Animation: def __init__(self, image_paths, scale_size, delay): # 加载并缩放所有帧 self.frames = [pygame.transform.scale(pygame.image.load(path), scale_size) for path in image_paths] self.delay = delay self.current_frame = 0 self.last_update_time = pygame.time.get_ticks() def update(self): current_time = pygame.time.get_ticks() if current_time - self.last_update_time > self.delay: self.current_frame += 1 if self.current_frame >= len(self.frames): self.current_frame = 0 self.last_update_time = current_time return self.frames[self.current_frame] # 创建两个动画对象 torchA = Animation( [f"torchA{i+1}.png" for i in range(4)], (48,96), 100 ) torchB = Animation( [f"torchB{i+1}.png" for i in range(4)], (48,96), 100 ) while True: for ev in pygame.event.get(): if ev.type == QUIT: pygame.quit() exit() clock.tick(60) screen.fill((0, 0, 0)) # 更新并绘制动画 screen.blit(torchA.update(), (100,100)) screen.blit(torchB.update(), (300,100)) pygame.display.flip()
补充说明
- 方案1适合简单场景,快速修改现有代码即可生效;
- 方案2适合多动画对象场景,代码结构清晰,便于后续维护和扩展。
内容的提问来源于stack exchange,提问作者newfile.py
相关产品推荐
相关产品推荐

