轻触按钮,无限循环

时间:2019-05-04 14:49:17

标签: python opengl pyglet

我需要通过按空格键开始无限循环,然后再次按空格键结束循环

@win.event
def on_draw():
    (some code of drawing)


@win.event
def on_key_press(symbol, modifiers):
    global x,y,z,t
    elif symbol == key.SPACE:
        t += 0.05
        x = ((1 - t) ** 3) * (-180) + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (0) + (t ** 3) * (200)
        y = ((1 - t) ** 3) * 70 + 3 * t * ((1 - t) ** 2) * (140) + 3 * (t ** 2) * (1 - t) * (140) + (t ** 3) * (
        70)
        z = ((1 - t) ** 3) * 0 + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (100) + (t ** 3) * (
        0)
        (here should be a function of endless moving (drawing) while Space haven't pressed again)

1 个答案:

答案 0 :(得分:1)

这不是正确的选择。您已经有了一个循环,即游戏循环。用它!

创建2个状态变量start_looprun_loop

start_loop = False
run_loop = False

如果按下 space ,则必须决定要做什么。
如果循环未运行(not run_loop),请通过设置start_loop = True.来启动循环 如果循环正在运行,请通过run_loop = False停止循环。

def on_key_press(symbol, modifiers):

    if symbol == key.SPACE:
        if not run_loop:
            start_loop = True
        else:
            run_loop = False

在主循环中,您必须区分3种情况。

  1. start_loopTrue。进行初始化并设置状态以在下一帧(start_loop = Falserun_loop = True)中运行循环
  2. run_loopTrue。在循环中执行代码
  3. 默认情况下,会绘制一些图形
def on_draw():

    global x,y,z,t

    if start_loop:
        start_loop = False
        run_loop = True

        t += 0.05
        x = ((1 - t) ** 3) * (-180) + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (0) + (t ** 3) * (200)
        y = ((1 - t) ** 3) * 70 + 3 * t * ((1 - t) ** 2) * (140) + 3 * (t ** 2) * (1 - t) * (140) + (t ** 3) * (70)
        z = ((1 - t) ** 3) * 0 + 3 * t * ((1 - t) ** 2) * (100) + 3 * (t ** 2) * (1 - t) * (100) + (t ** 3) * (0)

    elif run_loop:

        # this is the loop
        # [...] (here should be a function of endless moving (drawing) while Space haven't pressed again)
        pass

    else:

        # this is default
        # [...] (some code of drawing)

当然,您必须通过[schedule_interval添加一个计划功能,该功能以指定的间隔运行循环。

def run_loop(dt):
    on_draw()

pyglet.clock.schedule_interval(run_loop, 0.1) # run every tenth of a second
pyglet.app.run()