Search code examples
pythonpyglet

How to move objects in Pyglet using key inputs


So I am learning Pyglet. I want to know how can I move characters using the key input. I looked at the documentation and that didn't satisfy me. P.S. I think so you do movements with sprites, but I want to move a drawn Rectangle.

(Just the code I am running)

import pyglet
from pyglet.window import key, mouse
from pyglet import shapes
x = 250
window = pyglet.window.Window()
batch = pyglet.graphics.Batch()
rectangle = shapes.Rectangle(x, 300, 400, 200, color=(255, 22, 20), batch=batch)
@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.LEFT:
        x += 10
        print ('mystery')
@window.event
def on_draw():
    window.clear()
    batch.draw()

pyglet.app.run()

Solution

  • You need to change rectangle.x and rectangle.y not only x and y

    @window.event
    def on_key_press(symbol, modifiers):
        if symbol == key.LEFT:
            rectangle.x -= 10
        elif symbol == key.RIGHT:
            rectangle.x += 10
        elif symbol == key.UP:
            rectangle.y += 10
        elif symbol == key.DOWN:
            rectangle.y -= 10