python - 如何在pygame中检测鼠标悬停在图像(圆形)上
问题描述
如果图像检测到鼠标悬停,我需要缩放图像,但我不知道怎么做。pygame.mouse.get_pos()
我认为使用图像很难检测到它,rect
因为图像是圆形而不是矩形。尽管鼠标位于图像的角落,但它可能会检测到鼠标悬停,而不是触摸它。
解决方案
您可以使用勾股定理来计算鼠标与圆心之间的距离,或者只是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
如果您正在处理精灵。
推荐阅读
- angular - 样式化自定义面板菜单标签
- python - 如何在 python 中解析来自 Lambda 的 SNS 测试通知?
- c# - 将 Datagridview 行数据传递给新表单
- c# - 在预定义列表中查找下一步
- c# - 更改 Shell 类的后退按钮的覆盖文本的字体大小(以及,如果可能,其他字体格式属性)
- java - WebSphere JAX-WS 响应处理程序失败
- azure-devops - 具有条件手动批准作业的 DevOps 模板
- webpack - 将 webpack 块图导出到 json
- java - 为什么它说我缺少括号?
- php - 尝试使用 PHP 和 SQL 为我的游戏制作 hiscore 排行榜