Pygame collidepoint()工作不正常

2024-10-01 05:03:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个游戏,你砍树,并希望它,使你只能砍树半径为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

Tags: andtheintree游戏getif半径
1条回答
网友
1楼 · 发布于 2024-10-01 05:03:24

您必须评估坐标是否在一个范围内,在一个相同的条件下。你实际做的是:

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

此外,通过使用^{}可以简化算法。例如:

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

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, dy = (mouse_x - x, mouse_y - y)
        if dx*dx + dy*dy <= 50*50:
            countdown = 3
            destroy_tree = tree

相关问题 更多 >