imyxh
imyxh

Reputation: 164

(Pygame) Problems with Mouseover Detection

I've seen both of these posts, and still haven't got mouseover detection working. I'm developing a simple start menu for a game I'm working on for a friend; there are two pieces of text, and they are supposed to turn blue when hovered over.

However, they only turn blue when I hover my mouse in the upper-left corner: I'm assuming my code is detecting the original (unblitted and unpositioned) surface which is in the upper left corner, and converting that into a rect, then checking for .collidepoint(pygame.mouse.get_pos()).

How do I make it detect the already blitted and positioned text?

Here's my code (or at least the part that's causing trouble):

font = pygame.font.Font(os.path.join('.', 'bin', 'NOVEMBER.TTF'), 26)
playText = font.render("Play", True, lightGray)
settingsText = font.render("Options", True, lightGray)
setDisplay.fill(darkGray)
playText_rect = playText.get_rect()
settingsText_rect = settingsText.get_rect()

Then later, in my main loop:

if settingsText_rect.collidepoint(pygame.mouse.get_pos()):
        settingsText = font.render("Options", True, grayBlue)
        setDisplay.blit(settingsText, (rightBorder / 2 - settingsText.get_width() / 2 + 200, bottomBorder / 2 - settingsText.get_height() / 2 + 120))
    elif playText_rect.collidepoint(pygame.mouse.get_pos()):
        playText = font.render("Play", True, grayBlue)
        setDisplay.blit(playText, (rightBorder / 2 - playText.get_width() / 2 - 200, bottomBorder / 2 - playText.get_height() / 2 + 120))
    else:
        playText = font.render("Play", True, lightGray)
        settingsText = font.render("Options", True, lightGray)

Oh, and I'm on Ubuntu if it makes a difference.

Upvotes: 1

Views: 127

Answers (1)

sloth
sloth

Reputation: 101162

When you simply call .get_rect() on a Surface, the resulting Rect indeed has its x and y position set to 0.

An easy way to fix this is to use playText_rect and settingsText_rect for blitting instead of calculating the position in the main loop.

# calculate the position once and but the rect at that position
playText_rect = playText.get_rect(topleft=(rightBorder / 2 - playText.get_width() / 2 - 200, bottomBorder / 2 - playText.get_height() / 2 + 120))
settingsText_rect = settingsText.get_rect(topleft=(rightBorder / 2 - settingsText.get_width() / 2 + 200, bottomBorder / 2 - settingsText.get_height() / 2 + 120))

...

# use the rect as position argument for blit
setDisplay.blit(settingsText, settingsText_rect)

...

setDisplay.blit(playText, playText_rect)

Upvotes: 1

Related Questions