jwoojin9
jwoojin9

Reputation: 293

How to detect mouseover an image (circular) in pygame

I need to zoom an image if the image detects mouseover, but I don't know the way. I think it's hard to detect it using pygame.mouse.get_pos() and the image's rect because the image is a circle not a rectangle. It might detect the mouseover though the mouse is in the corner of the image, not touching it.

Upvotes: 1

Views: 1105

Answers (1)

skrx
skrx

Reputation: 20438

You can use the Pythagorean theorem to calculate the distance between the mouse and the circle center or just math.hypot. If the distance is less than the radius, the mouse and the circle collide.

Also, create a rect for the image which serves as the blit position and makes it easy to obtain the center point.

import math
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

radius = 60  # Circle radius.
IMAGE = pg.Surface((120, 120), pg.SRCALPHA)
pg.draw.circle(IMAGE, (225, 0, 0), (radius, radius), radius)
# Use this rect to position the image.
rect = IMAGE.get_rect(center=(200, 200))

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEMOTION:
            mouse_pos = event.pos  # Or `pg.mouse.get_pos()`.
            # Calculate the x and y distances between the mouse and the center.
            dist_x = mouse_pos[0] - rect.centerx
            dist_y = mouse_pos[1] - rect.centery
            # Calculate the length of the hypotenuse. If it's less than the
            # radius, the mouse collides with the circle.
            if math.hypot(dist_x, dist_y) < radius:
                print('collision')

    screen.fill(BG_COLOR)
    screen.blit(IMAGE, rect)
    pg.display.flip()
    clock.tick(60)

pg.quit()

You could also use masks for pixel-perfect collision detection or pygame.sprite.collide_circle if you're dealing with sprites.

Upvotes: 1

Related Questions