游戏 AI / 系统课时
用检测射线找到前方障碍
用检测射线找到前方障碍
角色要在真正撞到墙之前转向,首先必须知道前进方向上有没有障碍。本节建立一个最小前方射线模型,计算射线范围、命中距离和障碍相对位置,为后续生成避障转向量准备可靠输入。
学习目标
- 根据角色速度确定前方射线的方向与长度
- 计算射线与障碍物的最近命中距离
- 从障碍相对位置中提取前后与左右关系
前方射线要表达什么
最简单的感知模型可以从角色中心发出一条射线。射线起点是角色当前位置,方向通常采用当前速度的单位向量,长度则代表控制器愿意提前观察多远。
速度越高,角色在相同反应时间内移动得越远,因此感知距离通常也应随速度增加。可以把它理解为“固定安全距离 + 未来一小段时间可能走过的距离”,再限制到合理的最小值和最大值之间。

当角色几乎静止时,速度向量无法稳定提供朝向,此时应使用角色自身的 facing、forward 等朝向信息作为射线方向,而不是直接归一化零向量。
计算射线与圆形障碍的命中
下面使用纯二维数学实现一个可运行示例。为了把重点放在感知逻辑上,障碍物用圆表示;真实游戏中通常会直接调用物理引擎的 Raycast,再读取引擎返回的命中点、距离和法线。
from dataclasses import dataclass
import math
@dataclass
class Vec2:
x: float
y: float
def __add__(self, other: 'Vec2') -> 'Vec2':
return Vec2(self.x + other.x, self.y + other.y)
def __sub__(self, other: 'Vec2') -> 'Vec2':
return Vec2(self.x - other.x, self.y - other.y)
def __mul__(self, value: float) -> 'Vec2':
return Vec2(self.x * value, self.y * value)
def dot(self, other: 'Vec2') -> float:
return self.x * other.x + self.y * other.y
def length(self) -> float:
return math.hypot(self.x, self.y)
def normalized(self) -> 'Vec2':
length = self.length()
if length == 0:
raise ValueError('direction must not be zero')
return Vec2(self.x / length, self.y / length)
def ray_circle_hit(origin: Vec2, direction: Vec2, max_distance: float,
center: Vec2, radius: float) -> float | None:
direction = direction.normalized()
to_center = center - origin
# projection 表示障碍中心沿射线方向离起点多远。
projection = to_center.dot(direction)
if projection < 0:
return None
closest_sq = to_center.dot(to_center) - projection * projection
radius_sq = radius * radius
if closest_sq > radius_sq:
return None
offset = math.sqrt(radius_sq - closest_sq)
hit_distance = projection - offset
if hit_distance < 0:
hit_distance = 0.0
return hit_distance if hit_distance <= max_distance else None
position = Vec2(0.0, 0.0)
velocity = Vec2(4.0, 0.0)
obstacle_center = Vec2(3.0, 0.6)
obstacle_radius = 1.0
ray_length = 4.0
forward = velocity.normalized()
hit_distance = ray_circle_hit(
position, forward, ray_length, obstacle_center, obstacle_radius
)
relative = obstacle_center - position
longitudinal = relative.dot(forward)
left = Vec2(-forward.y, forward.x)
lateral = relative.dot(left)
print(f'hit_distance={hit_distance:.2f}')
print(f'longitudinal={longitudinal:.2f}')
print(f'lateral={lateral:.2f}')预期输出:
hit_distance=2.20
longitudinal=3.00
lateral=0.60hit_distance=2.20 表示射线前进 2.2 个单位就会碰到障碍边缘。longitudinal 为正,说明障碍中心在角色前方;lateral 为正,则表示它位于当前前进方向的左侧。
射线长度不要写成固定魔法值
固定射线长度在单一速度下可以工作,但速度变化后通常会出现两个极端:低速时看得过远,角色提前绕行;高速时看得太近,刚发现墙体就已经没有足够空间转向。
一种容易调试的计算方式是:
rayLength = baseDistance + speed * lookAheadTime
其中 baseDistance 保证低速时仍有最小感知范围,lookAheadTime 表示希望观察未来多长时间。最终值还应限制在业务允许的最小和最大范围内,避免极端速度产生不合理的长射线。
多个障碍时选择最近有效命中
一条射线可能同时指向多个碰撞体。局部避障通常只需要处理沿射线方向最先会撞到的有效障碍,因此可以过滤掉射线后方、感知距离之外以及不会与射线相交的对象,再选择最小的非负命中距离。
单条中心射线也有明显边界:它把角色近似成一个点。宽体型角色可能出现中心射线没有命中,但肩部已经擦到墙角的情况。常见改进是增加左右辅助射线、使用圆形或胶囊形 Cast,或者直接按照角色碰撞体尺寸进行膨胀检测。
当感知模块能够稳定给出射线方向、最近命中距离、命中点以及障碍相对左右位置后,避障控制器就不必再猜测环境。它可以根据这些几何信息提前产生侧向转向量,在真正发生碰撞之前修改运动轨迹。