如何在 pygame 中检测鼠标悬停在图像(圆形)上
How to detect mouseover an image (circular) in pygame
如果图像检测到鼠标悬停,我需要缩放图像,但我不知道方法。
我认为使用 pygame.mouse.get_pos()
和图像的 rect
很难检测到它,因为图像是圆形而不是矩形。它可能会检测到鼠标悬停,但鼠标位于图像的一角,而不是触摸它。
可以使用Pythagorean theorem to calculate the distance between the mouse and the circle center or just math.hypot
。如果距离小于半径,则鼠标与圆碰撞。
另外,为图片创建一个rect作为blit位置,方便获取中心点。
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()
如果您要处理精灵,也可以使用 masks for pixel-perfect collision detection or pygame.sprite.collide_circle
。
如果图像检测到鼠标悬停,我需要缩放图像,但我不知道方法。
我认为使用 pygame.mouse.get_pos()
和图像的 rect
很难检测到它,因为图像是圆形而不是矩形。它可能会检测到鼠标悬停,但鼠标位于图像的一角,而不是触摸它。
可以使用Pythagorean theorem to calculate the distance between the mouse and the circle center or just math.hypot
。如果距离小于半径,则鼠标与圆碰撞。
另外,为图片创建一个rect作为blit位置,方便获取中心点。
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()
如果您要处理精灵,也可以使用 masks for pixel-perfect collision detection or pygame.sprite.collide_circle
。