I have an image:
newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
I then display it on the screen:
screen.blit(newGameButton, (0,0))
How do I detect if the mouse is touching the image?
I have an image:
newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
I then display it on the screen:
screen.blit(newGameButton, (0,0))
How do I detect if the mouse is touching the image?
Use Surface.get_rect
to get a Rect
describing the bounds of your Surface
, then use .collidepoint()
to check if the mouse cursor is inside this Rect
.
Example:
if newGameButton.get_rect().collidepoint(pygame.mouse.get_pos()):
print "mouse is over 'newGameButton'"
I'm sure there are more pythonic ways to do this, but here is a simple example:
button_x = 0
button_y = 0
newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
x_len = newGameButton.get_width()
y_len = newGameButton.get_height()
mos_x, mos_y = pygame.mouse.get_pos()
if mos_x>button_x and (mos_x<button_x+x_len):
x_inside = True
else: x_inside = False
if mos_y>button_y and (mos_y<button_y+y_len):
y_inside = True
else: y_inside = False
if x_inside and y_inside:
#Mouse is hovering over button
screen.blit(newGameButton, (button_x,button_y))
Read more on the mouse in pygame, as well as surfaces in pygame.
Also here is an example closely related to this.