尝试每 0.25 秒更改一次移动角色的图像 PyGame [英] Trying to change image of moving character in every 0.25 seconds PyGame

查看:58
本文介绍了尝试每 0.25 秒更改一次移动角色的图像 PyGame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图通过在他走路时在 2 张图片之间切换来在 pygame 中动画"我的角色.我尝试使用这里提到的代码:在 PyGame 中,如何在不使用睡眠功能的情况下每 3 秒移动一次图像? 但结果不太好.事实上,我的角色在走路时只使用一个图像.这里是部分代码和一些变量:

So i am trying to 'animate' my character in pygame by changing between 2 pictures when he walks. I tried to use the code that was mentioned here: In PyGame, how to move an image every 3 seconds without using the sleep function? but it didn't turn out too well. In fact my character only uses one image when walking. here the part of the code and some variables:

  • 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)) 

为什么它不起作用?

推荐答案

在pygame中可以通过调用pygame.time.get_ticks(),它返回自 pygame.init() 被调用.请参阅 pygame.time 模块.

In pygame the system time can be obtained by calling pygame.time.get_ticks(), which returns the number of milliseconds since pygame.init() was called. See pygame.time module.

使用属性 self.walk_count 为角色设置动画.向类添加属性 animate_time 以指示何时需要更改动画图像.将当前时间与 draw() 中的 animate_time 进行比较.如果当前时间超过animate_time,增加self.walk_count并计算下一个animate_time.

Use an attribute self.walk_count to animate the character. Add an attribute animate_time to the class that indicates when the animation image needs to be changed. Compare the current time with animate_time in draw(). If the current time exceeds animate_time, increment self.walk_count and calculate the next 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)) 

这篇关于尝试每 0.25 秒更改一次移动角色的图像 PyGame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆