问题
我目前正在写一个小RPG。当它与精灵碰撞时,我设法让一名玩家射击并摧毁射弹。它运作良好,因为玩家是聪明的"当他和目标之间有一堵墙时,足以不射击。
我正在考虑如何将此方法移动到我的怪物身上。但是,如果目标与他之间存在障碍,我可以想到避免怪物射击的唯一方法是在两者之间画一条线并检查线是否与任何障碍物相交。
我还没有找到一种有效地做到这一点的方法。目前我正在考虑测试沿线的每一个点,但我认为这会大大降低游戏速度。
如果您对如何有效地检查线条是否与矩形发生碰撞有任何答案,我会很感激。
由于
ANSWER
感谢@ DCA-评论能够完全实现我的目标。我从框中得到了Bresenhams's线算法(cpoy /粘贴在我的functions.py模块中)。然后我编写了:
'''the range_ argument represents the maximum shooting distance at which the shooter will start firing. and obstacles is a list of obstacles, shooter and target are both pygame Sprites'''
def in_sight(shooter, target, range_, obstacles):
line_of_sight = get_line(shooter.rect.center, target.rect.center)
zone = shooter.rect.inflate(range_,range_)
obstacles_list = [rectangle.rect for rectangle in obstacles] #to support indexing
obstacles_in_sight = zone.collidelistall(obstacles_list)
for x in range(1,len(line_of_sight),5):
for obs_index in obstacles_in_sight:
if obstacles_list[obs_index].collidepoint(line_of_sight[x]):
return False
return True
答案 0 :(得分:1)
我认为您正在寻找的是一种视线算法。
查看Bresenhams's行算法或其他此类资源作为起点。
这是2d rogue-like和rpg中常用的算法。
我无法保证算法的效率或它在python中实现时的速度,但希望这能为你提供正确的方向。
另一个有用的算法可能是Raycasting。有许多python实现,并且很难找到。
希望这有帮助。