首页 > 解决方案 > Pygame:试图让整个精灵越过边界,而不仅仅是左上角的像素

问题描述

我正在尝试根据 astar 寻路算法使我的精灵移动。然而,在我实现它之后,我意识到精灵的移动只是根据左上角的像素。这意味着如果算法告诉它在越过边界后向上移动,那么一旦左上角的像素越过该边界,它就会这样做。但是,这意味着整个精灵实际上并没有越过,如果在其上方有障碍物,则会导致碰撞。有没有办法告诉它在向上移动之前向左移动更多] 1

def astar_ghost(pac,ghost):
    maze=astar.create_maze(screen_width,screen_height,obstacles) #creates a maze of 0s and 1s. The 1s represent the obstacles

    start=(ghost.gridloc[0],ghost.gridloc[1])
    end=(ghost.goal_node[0],ghost.goal_node[1])
    goal_node=astar.astar(maze,start,end)

    if goal_node==None:
        pass
    else:
        ghost.goal_node=goal_node

    game=True

    if ghost.goal_node[0]<ghost.gridloc[0]:#left
         print('move left')

         game=collision(pac,ghost) #collision is another function that checks for collision and returns True or False. If False, the game will be over
         ghost.left=True
         ghost.right=False
         ghost.up=False
         ghost.down=False

     elif ghost.goal_node[0]>ghost.gridloc[0]:#right
         print('move right')

         game=collision(pac,ghost)
         ghost.left=False
         ghost.right=True
         ghost.up=False
         ghost.down=False

    elif ghost.goal_node[1]<ghost.gridloc[1]:#up
         print('move up')

         game=collision(pac,ghost)
         ghost.left=False
         ghost.right=False
         ghost.up=True
         ghost.down=False

    elif ghost.goal_node[1]>ghost.gridloc[1]:#down
        print('move down')

        game=collision(pac,ghost)
        ghost.left=False
        ghost.right=False
        ghost.up=False
        ghost.down=True

标签: pythonpygame

解决方案


你在这里问了几个不同的问题。我将在这里回答我认为您要问的问题:有没有办法检查整个精灵是否越过边界,而不仅仅是左上角?. 所以,我的回答(请注意,这仅在您的边界线是线性的情况下才有效):您需要单独检查每个角落,然后,如果所有角落都已返回True,那么您继续前进。例子:

def collision(sprite1, boundary):
    def internal_collision(point, boundary):
        ... # The actual math happens here, returns True/False
    corners = []
    for h in [0, 1]:
        for j in [0, 1]:
            corners.append([sprite1.rect.x+(h*sprite1.rect.width),
                            sprite1.rect.y+(j*sprite1.rect.height)])
    corner_check = []
    for corner in corners:
        corner_check.append(internal_collision(corner, boundary))
    return all(corner_check)

我不知道你的代码是如何工作的,所以我尽量保持它的可塑性和可理解性,这样你就可以在你自己的代码中重新实现它。


推荐阅读