问题
我目前正在编写一个小型角色扮演游戏。我已经设法让玩家射击并在与 Sprite 碰撞时摧毁弹丸。它运作良好,因为玩家足够“聪明”,当他和目标之间有一堵墙时不会开枪。
我目前正在考虑如何将这种方法转移到我的怪物身上。但是如果目标和他之间有障碍物,我能想到的避免怪物射击的唯一方法是在两者之间画一条线,并检查这条线是否与任何障碍物相交。
我还没有找到有效执行此操作的方法。目前我正在考虑测试沿线的每个点,但我认为这会显着降低游戏速度。
如果您对如何有效地检查一条线是否与矩形发生碰撞有任何答案,我将不胜感激。
谢谢
回答
感谢@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
请您参考如下方法:
我认为您正在寻找的是视线算法。
查看Bresenhams's线算法或其他此类资源作为起点。
这是 2d rogue-like 和 rpg 中常用的算法。
我不能保证该算法的效率或它在 python 中实现时的速度,但希望这能为您指明正确的方向。
另一个有用的算法可能是光线转换。周围有很多 python 实现,并不难找到。
希望这对您有所帮助。