【问题标题】:How to detect mouseover an image (circular) in pygame如何在pygame中检测鼠标悬停在图像(圆形)上
【发布时间】:2019-03-24 21:40:34
【问题描述】:

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

【问题讨论】:

    标签: python image pygame mouseover


    【解决方案1】:

    您可以使用Pythagorean theorem 来计算鼠标与圆心之间的距离,或者只使用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 进行像素完美的碰撞检测,或者使用pygame.sprite.collide_circle 如果您正在处理精灵。

    【讨论】:

    • 非常感谢!你一定是个天才才知道这些事情!我希望你以后能帮助我。
    • 这只是每个人都在学校学习的一些数学知识和一点 pygame 知识。三角函数、向量和矩阵(用于 3D)对游戏开发非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多