【问题标题】:Trying to change image of moving character in every 0.25 seconds PyGame尝试每 0.25 秒改变移动角色的图像 PyGame
【发布时间】:2020-10-03 20:47:15
【问题描述】:

所以我试图在 pygame 中通过在他走路时在 2 张图片之间切换来“动画化”我的角色。我尝试使用这里提到的代码: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.x, self.y))
                if time.time() > self.clock + 0.50:
                    self.clock = time.time()
        else: 
            screen.blit(self.img, (self.x, self.y)) 

为什么它不起作用?

【问题讨论】:

  • 函数的第一行每次都会重置时钟。尝试删除该行。
  • 谢谢!我把这条线移到了我班级的 init 部分,谢谢!
  • 您可能会发现使用pygame.time.get_ticks() 比使用time.time() 更容易/更好,因为前者为您提供整数毫秒计数。

标签: python time pygame pygame-clock pygame-tick


【解决方案1】:

在 pygame 中可以通过调用pygame.time.get_ticks() 来获取系统时间,它返回自调用pygame.init() 以来的毫秒数。请参阅pygame.time 模块。

使用属性self.walk_count 为角色设置动画。将属性animate_time 添加到指示何时需要更改动画图像的类。将当前时间与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)) 

【讨论】:

    猜你喜欢
    • 2015-08-29
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多