简体   繁体   English

pygame的“定时事件”功能

[英]Pygame “Timed Event” function

I've never found a clear answer to how I could create a timed event in pygame, 对于如何在pygame中创建定时事件,我从未找到明确的答案,

I want to create a timed movement with duration and cooldown. 我想创建一个具有持续时间和冷却时间的定时动作。 (let's say 1s and 2s respectively for this example). (在本示例中,分别为1和2)。 Similar to an Evade or Dash skill in games 类似于游戏中的逃避或冲刺技能

I've reedited the code and: 我已经编辑了代码,并且:

dash_now = 0
dash_cooldown = 2
    if dash:
        while dash_now < 2 and dash_cooldown >= 0:
            dash_now +- clock.tick(60) / 1000
            player.dash()
            firing == False
        else:
            dash = not dash
            dash_now ==  0
            dash_cooldown == 3
            dash_cooldown +- clock.tick(60) / 1000

Not working so far... I must be commiting a stupid mistake over here and I can't see which it is. 到目前为止没有工作...我一定是在犯一个愚蠢的错误,我看不出它是什么。

Its actually pretty simple: 它实际上非常简单:

Lets say you have a timer variable 假设您有一个计时器变量

timer = 0

After that, during every iteration, you add the time that has passed since the last frame: 之后,在每次迭代中,您添加自上一帧以来经过的时间:

timer += my_clock.tick(60) / 1000

Finally, later in the code, you can check if it meets a certain threshold. 最后,在代码后面,您可以检查它是否满足特定阈值。

if timer >= 2:
    # Insert whatever you want

    timer = 0

Therefore your code can be greatly simplified like this, as long as youre not expecting to be in a loop for the entirety of the movement. 因此,只要您不希望整个运动陷入循环,就可以像这样大大简化您的代码。

self.dash_delay = 0
self.is_dashing = 0

def dash(self):
        if dash_delay < 0 and self.is_dashing < 2:

            self.rect.x += self.speedx * 2
            self.rect.y += self.speedy * 2
            self.is_dashing +- clock.tick(60) / 1000

        elif self.is_dashing > 2:
            self.dash_delay = 3
            self.is_dashing = 0

        self.dash_delay -= clock.tick(60) / 1000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM