简体   繁体   中英

how to move sprites using Python,Pyglet?

No matter how hard I try, the sprite does not move, the code is correct, I would not ask, but I have a hopeless situation, help.! I have already used KeyStateHandler but it doesn't work either.

import pyglet
from pyglet.window import keys

x = 300
y = 300                                           

w=pyglet.window.Window(600,600)
i = 
pyglet.resource.image("pl.png")
sprite = pyglet.sprite.Spite(i)

@w.event
def on_draw():
    w.clear()
    sprite.draw(x,y)
@w.event
def key(symbol, modifiers):
    if symbol == K.UP:
       x+=10

If you want to modify a global variable inside of a function, then you need to specify that it is global.

@w.event
def key(symbol, modifiers):
    global x
    if symbol == K.UP:
       x += 10

If you don't, you're actually just creating a local variable. x += 10 is the same thing as x = x + 10 . If you write this in a function and don't declare x as global, python will think that you want to create a local variable x that's equal to the global variable x plus 10. When the function exits, the local variable is destroyed and the global variable unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM