1

I want to know if there is a way to catching mouse hover on sprite object with Pyglet?

my_sprite = pyglet.sprite.Sprite(image, x, y)

something like this in Tkinter :

sprite.bind(circle, "<Enter>", on_enter)

1 Answers1

0

Below is a demo code for detecting mouse hover on a moving gif sprite, u can have a try and change it to what u like.

import pyglet
from pyglet.window import mouse


animation = pyglet.image.load_animation('ur_image_gif_path_like_xxx.gif')
bin = pyglet.image.atlas.TextureBin()
animation.add_to_texture_bin(bin)
sprite = pyglet.sprite.Sprite(img=animation)
window = pyglet.window.Window()

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

def update(dt):
    sprite.x += dt*10

@window.event
def on_mouse_motion(x, y, dx, dy):
    # print(x, y, dx, dy)
    image_width = sprite.image.get_max_width()
    image_height = sprite.image.get_max_height()
    if sprite.x+image_width>x>sprite.x and sprite.y+image_height>y>sprite.y:
        print("mouse hover sprite")
    else:
        print("mouse leave sprite")

pyglet.clock.schedule_interval(update, 1/60.)
pyglet.app.run()
Lau Real
  • 317
  • 1
  • 4
  • 15
  • Thank you very much for the answer :D, but the problems is when you have multiple `sprite object` (for ex 50 sprite on screen) and calculating like that for all sprite is such a tedious task. Is there any better way to do this ? thanks again – Trần Bảo Phúc Jan 03 '19 at 07:35
  • sorry, but I do have no other ideas if there are many sprites(say 1000 or more) to be calculated, besides, `image_width ` and `image_height` can be move out from function`on_mouse_motion` as global variables to reduce calculation pressure. – Lau Real Jan 03 '19 at 07:53