python - 如何在不停止整个代码的情况下让 Actor 跳跃?

标签 python pygame pgzero

我正在尝试让 dino 跳跃,但是当我在 dino 跳跃和下降之间使用 time.sleep(0.1) 时,整个游戏停止0.1秒。

我尝试过使用 time.sleep,仅此而已,因为我在网上找不到任何其他有用的信息。

def jump():
    dino.y -= 100
    time.sleep(0.1)
    dino.y += 100

def on_key_up(key):
    jump()

当我按下向上箭头时,整个游戏卡住 0.1 秒。

最佳答案

我建议使用计时器事件。当玩家跳跃时,然后通过 pygame.time.set_timer() 启动计时器。当定时器事件发生时,则完成跳转:

jump_delay = 100 # 100 milliseconds == 0.1 seconds
jump_event = pygame.USEREVENT + 1
def jump():
    dino.y -= 100

    # start a timer event which just appear once in 0.1 seconds
    pygame.time.set_timer(jump_event, jump_delay, True)

def on_key_up(key):
    jump()
# event loop
for event in pygame.event.get():

    # jump timer event
    if event.type == jump_event:
       dino.y += 100

# [...]

注意,在 pygame 中可以定义客户事件。每个事件都需要一个唯一的 ID。用户事件的 id 必须以 pygame.USEREVENT 开头。在本例中,pygame.USEREVENT+1 是计时器事件的事件 ID,用于完成跳转。


Pygame不是Pygame Zero .

无论如何,如果你使用Pygame Zero ,那么您可以使用 update 的耗时参数回调:

def uptate(dt):

耗时参数 (dt) 给出自纬度帧以来耗时(以秒为单位)。

创建一个状态 (jump),指示 dino 是否正在跳跃。还有一个时间 (jump_time),它说明跳跃必须持续多长时间:

jump = False
jump_time = 0.0

设置jump中的状态和时间:

def jump():
    global jump, jump_time
    dino.y -= 100
    jump = True
    jump_time = 0.1 # 0.1 seconds

减少update中的时间并完成跳转,分别休息jump状态,如果jump_time小于0.0:

def uptate(dt):

    if jump:
        jump_time -= dt
        if jump_time < 0:
            dino.y += 100
            jump = False

关于python - 如何在不停止整个代码的情况下让 Actor 跳跃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58327639/

相关文章:

python - 如何加载动画 GIF 并获取 Pygame 中的所有单独帧?

Python/PyGame : Get window size

python - pygame 零 - 向下移动图形

带参数的 python 子进程 popen

Python/flask汇总算法错误

Python加入整数列表

python - pygame 不显示我的图像

python - 未知 RT 错误消息

python - pygame - 移动图形( Actor )

python - 如何使 Pygame 零窗口全屏显示?