在Pygame中检测鼠标悬停的图像

mat*_*gan 4 python pygame game-engine

我有一张图片:

newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
Run Code Online (Sandbox Code Playgroud)

然后我在屏幕上显示它:

screen.blit(newGameButton, (0,0))
Run Code Online (Sandbox Code Playgroud)

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

slo*_*oth 13

使用Surface.get_rect获得Rect描述你的边界Surface,然后使用.collidepoint()来检查,如果鼠标光标这里面Rect.


例:

if newGameButton.get_rect().collidepoint(pygame.mouse.get_pos()):
    print "mouse is over 'newGameButton'"
Run Code Online (Sandbox Code Playgroud)


ham*_*pig 5

我确信还有更多 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))
Run Code Online (Sandbox Code Playgroud)

阅读有关 pygame 中的鼠标以及pygame 中的曲面的更多信息。

这里还有一个与此密切相关的例子。