为了账号安全,请及时绑定邮箱和手机立即绑定

Pygame:试图让整个精灵穿过边界而不仅仅是左上角的像素

Pygame:试图让整个精灵穿过边界而不仅仅是左上角的像素

qq_笑_17 2022-12-06 15:23:24
我正在尝试根据 astar 寻路算法让我的精灵移动。然而,在我实现它之后,我意识到精灵的移动只是按照左上角的像素。这意味着如果算法告诉它在越过边界后向上移动,一旦左上角像素越过该边界,它就会这样做。然而,这意味着整个精灵实际上并没有穿过,如果它上方有障碍物就会导致碰撞。有没有办法告诉它在向上移动之前向左移动更多] 1def 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
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

您在这里问了几个不同的问题。我会在这里回答我认为你想问的问题:有没有办法检查整个精灵是否已经越过边界,而不仅仅是左上角?. 所以,我的回答(请注意,这仅在您的边界线是线性的情况下才有效):您需要单独检查每个角,然后,如果所有角都返回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)

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


查看完整回答
反对 回复 2022-12-06
  • 1 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号