Skip to content
Advertisement

How do I add a border to a sprite when the mouse hovers over it, and delete it after the mouse stops?

I have a sprite, and I want it to be so that when the mouse hovers over it, it places a small border around the sprite, and when it leaves, delete that border. How would I go about doing this?

Sprite Class:

JavaScript

I can add more code if required. Thank you!

Advertisement

Answer

Copy the image and draw a rectangle around it:

JavaScript

Check if the mouse is on the image with pygame.Rect.collidepoint and select the image:

JavaScript

This all is explained in the answers to the question Pygame mouse clicking detection.

Also note that pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, but it returns a rectangle that always starts at (0, 0) since a Surface object has no position.
The Surface is placed at a position on the display with the blit function.

You’ve to set the location of the rectangle, either by a keyword argument, e.g:

JavaScript

Store the mouse position in an attribute of the object. kill the Sprite when the mouse hovers over the Sprite and the mouse position does not change for som frames (e.g. 10):

JavaScript

Minimal example

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement