Pyglet 未调用 on_draw

Pyglet not calling on_draw

我正在尝试制作一款简单的游戏,但遇到了问题

这是我的代码:

from myvector import myVector
from car import Car
import pyglet


width = 1000
height = 600
agent = None
agent = Car(int(width/2), int(height/2))
window = pyglet.window.Window()
window.set_size(width,height)


@window.event
def on_key_press(symbol, modifiers):
    if symbol == 119:  # w
        agent.applyForce(myVector(-1, 0))
    if symbol == 115:  # s
        agent.applyForce(myVector(1, 0))
    if symbol == 97:  # a
        agent.applyForce(myVector(0, -1))
    if symbol == 100:  # d
        agent.applyForce(myVector(0, 1))


@window.event
def on_draw():
    window.clear()
    agent.update()
    agent.sprite.draw()
    print(1)


if __name__ == "__main__":
    pyglet.app.run()

问题是 on_draw 只有当我在键盘上输入内容时才会调用事件

我正在使用 python 3.6 和最新的 pyglet 包

我在互联网上什么也没找到 为什么会这样?

可能是装饰函数的问题。

不要装饰 on_draw,而是用您自己的函数声明替换 window 对象的 on_draw 函数:

请参阅 on_mouse_press 上的此示例,该示例已替换为自己的声明。

@window.event
def on_mouse_press(x, y, button, modifiers):
    global state, image
    if button == pyglet.window.mouse.LEFT:
        print('mouse press')
        if state:
            state = False
        else:
            state = True

替换为

import pyglet


image = pyglet.resource.image('test.png')
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2

state = True


def on_draw():
    print('on_draw() called')
    window.clear()
    if state:
        image.blit(window.width // 2, window.height // 2)


def on_mouse_press(x, y, button, modifiers):
    global state
    print('mouse pressed')
    if state:
        state = False
    else:
        state = True


window = pyglet.window.Window()
window.on_draw = on_draw
window.on_mouse_press = on_mouse_press

pyglet.app.run()

Pyglet 仅在事件发生时调用 on_draw。使用 pyglet.clock.schedule_interval 通过计时器发明连续调用函数。这导致 on_draw 也被触发:

@window.event
def on_draw():
    window.clear()
    agent.update()
    agent.sprite.draw()
    print(1)

def update(dt):
    # update objects
    # [...]
    pass

if __name__ == "__main__":
    pyglet.clock.schedule_interval(update, 1/60) # schedule 60 times per second
    pyglet.app.run()