问题
我正在编写一个小型的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