簡體   English   中英

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 包

我在互聯網上什么也沒找到,為什么會發生這種情況?

Pyglet 僅在事件發生時調用on_draw 使用pyglet.clock.schedule_interval通過計時器發明連續調用函數。 on_draw導致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()

這可能是裝飾器功能的問題。

不要裝飾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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM