Pygame。有效检测与精灵的线碰撞

Pygame. Efficient detection of line collision with sprite

问题

我目前正在写一个小角色扮演游戏。我已经设法让玩家射击并在与精灵碰撞时摧毁弹丸。它运作良好,因为玩家 "smart" 足以在他和目标之间有一堵墙时不射击。

我目前正在考虑如何将此方法转移到我的怪物中。但是如果目标和他之间有障碍物,我能想到的避免怪物射击的唯一方法是在两者之间画一条线,并检查这条线是否与任何障碍物相交。

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

如果您对如何有效检查一条线是否与矩形发生碰撞有任何答案,我将不胜感激。

谢谢

回答

感谢@DCA- 的评论能够实现我正在寻找的东西。我从盒子里得到了 Bresenhams's 直线算法(cpoy/pasted 它在我的 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 实现,并不难找到。

希望对您有所帮助。