Pygame collidepoint()无法正常工作

问题描述 投票:0回答:1

我正在制作一个游戏,其中您砍树并想要砍树,以便您只能砍掉您在游戏中位置(以正方形表示)的50像素半径(每个方向上大约1棵树)内的树。问题是,当我对其进行测试时,我发现它只能工作一次,这意味着您仅需采取行动即可停止半径障碍的工作,并且可以破坏任何树木。有人可以告诉我为什么会这样以及如何解决吗?代码如下:

# I'll only put in the bit that makes the bug
# Tree objects are sorted in a Tree class with a method destroy() to destroy the tree
for tree in trees:
            if pygame.mouse.get_pressed()[0] and tree.trunk.collidepoint(pygame.mouse.get_pos()):
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    print('clicked tree') # For testing purposes
                    if mouse_x < x + 51 and mouse_y < y + 51:
                        countdown = 3
                        destroy_tree = tree
                    elif mouse_x < x + 51 and mouse_y < y - 51:
                        countdown = 3
                        destroy_tree = tree
                    elif mouse_x < x - 51 and mouse_y < y - 51:
                        countdown = 3
                        destroy_tree = tree
                    elif mouse_x < x - 51 and mouse_y < y + 51:
                        countdown = 3
                        destroy_tree = tree
python python-3.x pygame click
1个回答
0
投票

您必须评估它的坐标处于一个条件的范围内。您实际执行的操作类似于:

if x < value + 50:
   countdown = 3
elif x > value - 50:
   countdown = 3

其中一个条件总是被满足,并且在任何情况下都设置为countdown

条件必须是:

if x - 51 < mouse_x < x + 51:
    if y - 51 < mouse_y < y + 51:
        countdown = 3
        destroy_tree = tree

此外,可以使用abs()简化算法。例如:

abs()

或者,您可以计算mouse_x, mouse_y = pygame.mouse.get_pos() for tree in trees: if pygame.mouse.get_pressed()[0] and tree.trunk.collidepoint((mouse_x, mouse_y)): print('clicked tree') # For testing purposes dx = mouse_x - x dy = mouse_y - y if abs(dx) <= 50 and abs(dy) <= 50: countdown = 3 destroy_tree = tree

Euclidean distance
© www.soinside.com 2019 - 2024. All rights reserved.