python - 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
解决方案
你在这里问了几个不同的问题。我将在这里回答我认为您要问的问题:有没有办法检查整个精灵是否越过边界,而不仅仅是左上角?. 所以,我的回答(请注意,这仅在您的边界线是线性的情况下才有效):您需要单独检查每个角落,然后,如果所有角落都已返回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)
我不知道你的代码是如何工作的,所以我尽量保持它的可塑性和可理解性,这样你就可以在你自己的代码中重新实现它。
推荐阅读
- android - Android - Exoplayer - 渐进式直播 - Mpeg2 - 音频问题
- c++ - 为什么在 C++ 中使用非类型参数?
- vb.net - 防止停靠在绘制的矩形上
- dynamics-crm - 无法在 Dynamics 365 销售中将导入产品的状态设置为“活动”
- css - CSS Grid 项目 div 周围的边框
- revit-api - Xceed AvalonDock - Revit MainWindow.FindFirstChild 返回 nul
- jenkins-pipeline - 我如何将变量从 jenkins 文件传递到 terraform
- java - 为什么 stopService 只能在一台设备上运行?
- python - Python:随机梯度下降的代码是如何工作的?
- postgresql - 强制某些复合类型字段是唯一的?