Search code examples
pythonpython-3.xpyglet

Pyglet not calling on_draw


I'm trying to make a simple game but I'm having issues

this is my code:

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

problem is on_draw event is only called when I input something on keyboard

I'm using python 3.6 and latest pyglet package

I found nothing on internet why is this happening?


Solution

  • Pyglet invokes on_draw only if an event occurs. Use pyglet.clock.schedule_interval to continuously invoke a function by a timer invent. That causes that on_draw is triggered, too:

    @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()