检查鼠标位置是否在区域 pygame 中

问题描述

我尝试在 rect 对象的矩阵中找到与鼠标位置碰撞但不起作用的 rect

def search_immagine(tab,event_pos):
   for i in range(tab[0]):
       for j in range(tab[0]): #matrix square
           surface=tab[i][j]
           surface=surface.get_rect()
           if surface.collidepoint(event_pos):
                   return True

while not finished:
   for event in pygame.event.get():
       if event.type==pygame.QUIT:
           cfinished=True
       if event.type==pygame.MOUSEBUTTONDOWN:
           search_image(image,event.pos)

解决方法

pygame.Surface.get_rect.get_rect() 返回一个具有 Surface 对象大小的矩形,但它返回一个矩形,它总是从 (0,0) 开始,因为 Surface对象没有位置。
当 Surface blit 到显示器时,它被放置在一个位置。

您必须通过关键字参数设置矩形的位置,例如:

def search_immagine(tab,event_pos):
    for i in range(tab):
        for j in range(tab[0]): #matrix square

            x = ... # x coordinate of tab[i][j] = (i * widht)
            y = ... # y coordinate of tab[i][j] = (j * height)

            surface_rect = surface.get_rect(topleft = (x,y))
            if surface_rect.collidepoint(event_pos):
                return True