2012-08-07 83 views
4

圖像我有一個形象:檢測鼠標懸停在Pygame的

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

我這時屏幕上顯示:

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

如何檢測如果鼠標觸摸圖像?

回答

11

使用Surface.get_rect獲得Rect描述您Surface的界限,然後用.collidepoint()檢查,如果鼠標光標這裏面Rect


例子:

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

如果你有一個以上的按鈕或表面,使它對每次要檢查你移動光標的列表。 – 2012-08-13 16:12:56

2

我敢肯定有更Python的方式來做到這一點,但這裏是一個簡單的例子:

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就是一個與此密切相關的例子。