0
\$\begingroup\$

I'm making a game menu in Pygame, consider the following block of code:

pygame.init()
...
exit_button = pygame.image.load(r'/home/salem/Documents/MyGame/exit_b.png').convert_alpha()
cursor = pygame.image.load(r'/home/salem/Documents/MyGame/clicker.png').convert_alpha()
mouse = pygame.mouse.get_pos()
x, y = mouse
cursor_x = x + cursor.get_width() / 2
cursor_y = y + cursor.get_height() / 2

while 1:
...
menu.blit(exit_button, (10, 555))
menu.blit(cursor, (cursor_x, cursor_y))
if exit_button.get_rect(x=10, y=555).collidepoint(mouse):
    exit()
pygame.display.update()
...

I'm experiencing some problems with the pygame.mouse module and get_rect method. They're not working correctly.

If I get the mouse position on the exit_button image while the script is running, nothing happens and it doesn't exit!

Furthermore, for some reason, the cursor's image is not being displayed, I can only see the system's cursor while moving the mouse though it's remarkably different from the cursor's image. (the system's cursor is black while the other one is white) At first, I thought they could be merged together, so to check that, I changed the cursor's coordinates but still the same result!

\$\endgroup\$
3
  • \$\begingroup\$ Your code snippet doesn't seem to ever update mouse or cursor_x or cursor_y, is that representative of your real running code? You should also consider always sharing a minimal verifiable example of your issue. \$\endgroup\$
    – user35344
    Jun 26, 2021 at 14:09
  • \$\begingroup\$ @Tyyppi_77 yeah that's my real code \$\endgroup\$
    – Salem
    Jun 26, 2021 at 14:11
  • \$\begingroup\$ In fact, I barely work with these methods, that's why I'm messing up with them \$\endgroup\$
    – Salem
    Jun 26, 2021 at 14:11

1 Answer 1

1
\$\begingroup\$

You are not ever updating the cursor position so the code will only check collisions at whatever the cursor position happens to be immediately after initialization.

If you want to check against the real position of the cursor, you need to call pygame.mouse.get_pos() again each iteration of the game loop, and of course then recalculate cursor_x and cursor_y using the new updated mouse position to make sure your cursor image is rendererd in the correct position.

\$\endgroup\$
1
  • \$\begingroup\$ Oh yeah that's true! I can't realize how didn't I pay attention to that ! hahaha thanks ! \$\endgroup\$
    – Salem
    Jun 26, 2021 at 14:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .