FroDK
FroDK

Reputation: 61

Pygame mouse over detect

I have code that determines whether the mouse cursor is over an object or not. But the problem is that it outputs a lot of print to the console. How do I make sure that if the cursor was over an object, it prints once?

if player.rect.collidepoint(pygame.mouse.get_pos()):
    mouse_over = True
    print(True)
    player.image.fill(RED)
else:
    mouse_over = False
    print(False)
    player.image.fill(GREEN)

I seem stupid. I had the definition of the variable mouse_over = 0 in a loop. I moved it from there and now everything works, thank you very much to everyone

Upvotes: 2

Views: 115

Answers (2)

SanticL
SanticL

Reputation: 56

This may sound a little elementary, but have you tried adding a flag? You already have a boolean with mouse_over, so it makes sense to me to have something like:

if player.rect,collidepoint(pygame.mouse.get_pos()):
    if(mouse_over==False):
        mouse_over=True
        print(True)
        player.image.fill(RED)
else:
    if(mouse_over==True):
        mouse_over=False
        print(False)
        player.image.fill(GREEN)

In this way, mouse_over acts as a flag and only allows the print statement to run once and to change the image.fill once. Image.fill can be changed to run every time just by getting rid of one indent.

Although, I'm not sure what you are using mouse_over for, so you may decide to create a new flag. It will still have to be checked and changed like how mouse_over is here, just with a different variable name.

Upvotes: 1

Jab
Jab

Reputation: 27515

Just use another if statement to see if it's already been in the rect. And don't print when it's out.

if player.rect.collidepoint(pygame.mouse.get_pos()):
    if not mouse_over:
        print(True)
    mouse_over = True
    player.image.fill(RED)
else:
    mouse_over = False
    player.image.fill(GREEN)

Upvotes: 0

Related Questions