首页 > 解决方案 > 如何在pygame中检测鼠标悬停在图像(圆形)上

问题描述

如果图像检测到鼠标悬停,我需要缩放图像,但我不知道怎么做。pygame.mouse.get_pos()我认为使用图像很难检测到它,rect因为图像是圆形而不是矩形。尽管鼠标位于图像的角落,但它可能会检测到鼠标悬停,而不是触摸它。

标签: pythonimagepygamemouseover

解决方案


您可以使用勾股定理来计算鼠标与圆心之间的距离,或者只是math.hypot. 如果距离小于半径,鼠标和圆碰撞。

此外,为图像创建一个矩形,作为 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()

您还可以使用遮罩进行像素完美的碰撞检测,或者pygame.sprite.collide_circle如果您正在处理精灵。


推荐阅读