【问题标题】:Detect mouseover an image in Pygame在 Pygame 中检测鼠标悬停在图像上
【发布时间】:2012-08-07 12:30:01
【问题描述】:

我有一张图片:

newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()

然后我将它显示在屏幕上:

screen.blit(newGameButton, (0,0))

如何检测鼠标是否正在触摸图像?

【问题讨论】:

    标签: python pygame game-engine


    【解决方案1】:

    使用Surface.get_rect 获取描述Surface 边界的Rect,然后使用.collidepoint() 检查鼠标光标是否在此Rect 内。


    示例:

    if newGameButton.get_rect().collidepoint(pygame.mouse.get_pos()):
        print "mouse is over 'newGameButton'"
    

    【讨论】:

    • 如果您有多个按钮或 Surfaces,请将其设置为每次移动光标时都要检查的列表。
    【解决方案2】:

    我确信还有更多的 Pythonic 方法可以做到这一点,但这里有一个简单的例子:

    button_x = 0
    button_y = 0
    newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
    x_len = newGameButton.get_width()
    y_len = newGameButton.get_height()
    mos_x, mos_y = pygame.mouse.get_pos()
    if mos_x>button_x and (mos_x<button_x+x_len):
        x_inside = True
    else: x_inside = False
    if mos_y>button_y and (mos_y<button_y+y_len):
        y_inside = True
    else: y_inside = False
    if x_inside and y_inside:
        #Mouse is hovering over button
    screen.blit(newGameButton, (button_x,button_y))
    

    阅读mouse in pygamesurfaces in pygame 的更多信息。

    here 也是一个与此密切相关的示例。

    【讨论】:

    • 如何检测鼠标是否在同时在鼠标按钮被按住的同时悬停在某物上?
    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多