首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在电子游戏中检测鼠标对图像(圆形)的影响

如何在电子游戏中检测鼠标对图像(圆形)的影响
EN

Stack Overflow用户
提问于 2018-10-20 02:00:06
回答 1查看 799关注 0票数 1

我需要放大图像,如果图像检测到鼠标,但我不知道的方式。我认为很难用pygame.mouse.get_pos()和图像的rect来检测它,因为图像是一个圆,而不是一个矩形。虽然鼠标在图像的角落,但它可能检测到鼠标,而不是触摸它。

EN

Stack Overflow用户

回答已采纳

发布于 2018-10-20 07:13:53

您可以使用毕达哥拉斯定理计算鼠标与圆心之间的距离,也可以只计算math.hypot。如果距离小于半径,鼠标和圆环就会发生碰撞。

另外,为图像创建一个矩形,作为blit的位置,这样就可以很容易地获得中心点。

代码语言:javascript
运行
复制
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

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52901809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档