W W
W W

Reputation: 23

How to drag .png from x,y to x1,y1 by draging with mouse in pyglet window

I know how to make a window, I know how to display an image, I know how to move it in a given way according to given coordinates. I would like to move the image with the mouse. Pick up from one place and drop in another. Inside the same pyglet window. How to do something like that? Someone would be kind enough to point me to some code example.

Upvotes: 2

Views: 272

Answers (1)

Rabbid76
Rabbid76

Reputation: 210877

PyGlet has a on_mouse_drag event. See Mouse events.

Create a pyglet.sprite

sprite = pyglet.sprite.Sprite(image)

and change the position of the sprite when the mouse is on the the sprite:

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    if sprite.x < x < sprite.x + sprite.width and sprite.y < y < sprite.y + sprite.width:
        sprite.x += dx
        sprite.y += dy

Minimal example:

from pyglet.gl import *

window = pyglet.window.Window(300, 300, "drag", resizable = True)

image = pyglet.image.load('banana64.png')
sprite = pyglet.sprite.Sprite(image, x=20, y=20)

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    if sprite.x < x < sprite.x + sprite.width and sprite.y < y < sprite.y + sprite.width:
        sprite.x += dx
        sprite.y += dy

@window.event
def on_draw():
    window.clear()
    sprite.draw()
    
pyglet.app.run()

Upvotes: 2

Related Questions