如何使用碰撞矩形或其他方式从鼠标坐标获取对象(或其在 NumPy 数组中的索引)? (Pygame 二维)

How to get object(or it's index in NumPy array) from mouse coordinates using collide rect or something else? (Pygame 2D)

基本上,我有一个 NumPy 矩形数组,用于存储它们的颜色和位置。 我希望能够比较我的鼠标位置并单击矩形的位置并从数组中获取索引或对象本身。

我是否必须遍历数组中的每个方块并比较项目的坐标?

结构如下:

Cube[Face][Horizontal-Line][Square] = np.array([colour, pygame.Rect(x, y, size, size)])

怎么做最有效。我正在考虑使用 colliderect() 方法,但我不知道如何实现它。

https://i.stack.imgur.com/oQyxn.png

如果您需要更多数据,我会提供

我建议创建一个矩形列表:

rect_list = [rect1, rect2, rect3 ...]

鼠标位置(下图mouse_pos)是一个点,不是矩形。使用collidepoint求矩形与点的交点:

collide_rect_index = -1
for i, rect in enumerate(rect_list):
    if rect.collidepoint(mouse_pos):
        collide_rect_index = i
        break

或者您可以使用 collidelist():

Test whether the rectangle collides with any in a sequence of rectangles. The index of the first collision found is returned. If no collisions are found an index of -1 is returned.

在鼠标位置创建一个 1x1 的矩形,并在矩形列表中找到碰撞矩形的索引:

mouse_rect = pygame.Rect(*mouse_pos, 1, 1)
collide_rect_index = mouse_rect.collidelest(rect_list)

但是,如果您有网格,则可以通过将鼠标位置 (mouse_pos) 除以图块的大小来找到图块索引 (rowcolumn) (tile_size)。行和列必须是完整的。因此,您必须使用地板除法 (//) 运算符:

column = mouse_pos[0] // tile_size
row    = mouse_pos[1] // tile_size