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

时间:2012-08-07 12:30:02

标签: python pygame game-engine

我有一张图片:

newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
然后我将其显示在屏幕上:

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

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

2 个答案:

答案 0 :(得分:12)

使用Surface.get_rect获取描述Rect范围的Surface,然后使用.collidepoint()检查鼠标光标是否位于此Rect内。


示例:

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

答案 1 :(得分: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 pygame以及surfaces in pygame

同样here是与此密切相关的一个例子。