问题描述
因此,我试图通过在pygame中走路时在两张图片之间切换来“动画化”我的角色。我尝试使用此处提到的代码:In PyGame,how to move an image every 3 seconds without using the sleep function?,但结果并不太好。实际上,我的角色走路时只使用一张图像。这里是代码的一部分和一些变量:
- self.xchange:在x轴上更改
- self.img:角色静止时的图像
- self.walk1和self.walk2:我要使用的两个图像 动画我的角色
- self.x和self.y是坐标 屏幕是表面
。
def draw(self):
self.clock = time.time()
if self.xchange != 0:
if time.time() <= self.clock + 0.25:
screen.blit(self.walk1,(self.x,self.y))
elif time.time() > self.clock + 0.25:
screen.blit(self.walk2,self.y))
if time.time() > self.clock + 0.50:
self.clock = time.time()
else:
screen.blit(self.img,self.y))
为什么不起作用?
解决方法
在pygame中可以通过调用pygame.time.get_ticks()
来获取系统时间,它返回自调用pygame.init()
以来的毫秒数。请参阅 pygame.time
模块。
使用属性 self.walk_count
为角色设置动画。向类添加属性 animate_time
,指示何时需要更改动画图像。将当前时间与 animate_time
中的 draw()
进行比较。如果当前时间超过animate_time
,则增加self.walk_count
并计算下一个animate_time
。
class Player:
def __init__(self):
self.animate_time = None
self.walk_count = 0
def draw(self):
current_time = pygame.time.get_ticks()
current_img = self.img
if self.xchange != 0:
current_img = self.walk1 if self.walk_count % 2 == 0 else self.walk2
if self.animate_time == None:
self.animate_time = current_time + 250 # 250 milliseconds == 0.25 seconds
elif current_time >= self.animate_time
self.animate_time += 250
self.walk_count += 1
else:
self.animate_time = None
self.walk_count = 0
screen.blit(current_img,(self.x,self.y))