尝试每 0.25 秒更改移动角色的图像PyGame

Trying to change image of moving character in every 0.25 seconds PyGame

所以我试图 'animate' 我在 pygame 中的角色,当他走路时在 2 张图片之间切换。我尝试使用此处提到的代码:In PyGame, how to move an image every 3 seconds without using the sleep function? 但结果并不理想。事实上,我的角色在走路时只使用一个图像。这里是代码的一部分和一些变量:

.

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.x, self.y))
                if time.time() > self.clock + 0.50:
                    self.clock = time.time()
        else: 
            screen.blit(self.img, (self.x, self.y)) 

为什么不起作用?

在pygame中可以调用pygame.time.get_ticks(), which returns the number of milliseconds since pygame.init() was called. See pygame.time模块获取系统时间

使用属性 self.walk_count 为角色设置动画。将属性 animate_time 添加到 class 以指示何时需要更改动画图像。将当前时间与 draw() 中的 animate_time 进行比较。如果当前时间超过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))