【发布时间】: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