【问题标题】:Pygame. Efficient detection of line collision with sprite游戏。高效检测线与精灵的碰撞
【发布时间】:2016-06-06 13:30:23
【问题描述】:

问题

我目前正在编写一个小型 rpg。当弹丸与精灵碰撞时,我设法让玩家射击并摧毁弹丸。这很有效,因为玩家足够“聪明”,不会在他和目标之间有一堵墙时射击。

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

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

如果您对如何有效地检查直线是否与矩形相撞有任何答案,我将不胜感激。

谢谢

回答

感谢@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

【问题讨论】:

    标签: python-2.7 pygame line collision-detection


    【解决方案1】:

    我认为您正在寻找的是一种视线算法。

    查看Bresenhams's 行算法或其他此类资源作为起点。

    这是 2d rogue-like 和 rpg 中常用的算法。

    我不能保证算法的效率或在 python 中实现时的速度,但希望这可以为您指明正确的方向。

    另一个有用的算法可能是光线投射。周围有很多python实现,不难找到。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      相关资源
      最近更新 更多