Pygame. 高效检测精灵与线段碰撞

3

问题

我正在编写一个小型的RPG游戏。我已经成功让玩家进行射击,并在弹丸与精灵碰撞时摧毁它。这很有效,因为玩家足够“聪明”,当他和目标之间有墙壁时不会进行射击。

我现在正在考虑如何将此方法移植到我的怪物身上。但是,我能想到的唯一避免怪物在目标和它之间有障碍物时进行射击的方法是在两者之间画一条线,并检查该线是否与任何障碍物相交。

我还没有找到有效地执行此操作的方法。目前,我正在考虑测试沿着该线的每个点,但我认为这会严重减缓游戏速度。

如果您知道如何高效地检查一条线是否与矩形相撞,请告诉我。

谢谢

答案

感谢@DCA-的评论,我成功地实现了我所寻找的功能。我从Bresenham's line algorithm大致复制/粘贴了代码(放在了我的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
1个回答

1
我认为您需要的是一种视线算法。
可以从Bresenham's线算法或其他类似资源开始研究。
这是2D游戏和RPG中常用的算法。
我无法保证该算法在Python中实现的效率或速度,但希望这能为您指明正确的方向。
另一个有用的算法可能是Raycasting。有许多Python实现可供使用,不难找到。
希望对您有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接