游戏 AI / 系统课时
用速度和转向力驱动移动
用速度和转向力驱动移动
本篇把 Steering Behavior 落到可执行的运动更新:先根据目标生成期望速度,再计算转向力,最后用加速度更新速度与位置。完成后,NPC 不再瞬间改变方向,而会受到最大速度和最大加速度约束。
学习目标
- 理解速度、期望速度与转向力的关系
- 实现一个最小可运行的 Steering 更新循环
- 知道最大速度和最大转向力分别控制什么
从期望速度得到转向力
设当前速度为 ,目标方向为单位向量 ,最大速度为 。期望速度可以写成 ,再用当前速度与期望速度之差得到转向意图:。
这个差值的关键作用是“逐步改变速度”,而不是直接替换速度。再限制转向力的最大长度,就能控制 NPC 转弯和加速的激烈程度。

最小运动更新
下面的 Python 示例用二维向量实现最小模型。它不依赖游戏引擎,方便先验证公式与更新顺序;真实项目中只需要把位置、速度和时间步长接到引擎对象即可。
python
import math
def length(x, y):
return math.hypot(x, y)
def update(position, velocity, target, max_speed, max_steering, dt):
dx = target[0] - position[0]
dy = target[1] - position[1]
distance = length(dx, dy)
if distance == 0:
return position, velocity
direction = (dx / distance, dy / distance)
desired = (direction[0] * max_speed, direction[1] * max_speed)
steering = (desired[0] - velocity[0], desired[1] - velocity[1])
steering_length = length(*steering)
if steering_length > max_steering:
scale = max_steering / steering_length
steering = (steering[0] * scale, steering[1] * scale)
new_velocity = (
velocity[0] + steering[0] * dt,
velocity[1] + steering[1] * dt,
)
speed = length(*new_velocity)
if speed > max_speed:
scale = max_speed / speed
new_velocity = (new_velocity[0] * scale, new_velocity[1] * scale)
new_position = (
position[0] + new_velocity[0] * dt,
position[1] + new_velocity[1] * dt,
)
return new_position, new_velocity
position = (0.0, 0.0)
velocity = (0.0, 0.0)
position, velocity = update(position, velocity, (10.0, 0.0), 4.0, 2.0, 0.5)
print(f"position={position}, velocity={velocity}")预期输出
text
position=(0.5, 0.0), velocity=(1.0, 0.0)这里的更新顺序很重要:先根据目标得到期望速度,再限制 steering,随后更新速度并再次限制最大速度,最后才用新速度推进位置。这样即使目标方向突然改变,速度也会经过若干帧逐步调整。
两个参数分别控制什么
max_speed 决定 NPC 最快能移动多快;它主要限制平移速度。max_steering 决定速度改变得有多快;值越小,转向和加速越柔和,但追踪目标可能更慢。
时间步长 dt 也必须参与更新。相同的 steering 在不同帧率下如果不乘以 dt,运动速度就会随帧率变化,因此不要把“每帧移动多少”当成固定的世界速度。
到达目标时不要继续硬追
接近目标后,可以把期望速度逐渐降低,而不是始终要求达到 max_speed。最简单的做法是在目标半径内直接减速或停止。这样能避免 NPC 到达目标后越过目标点,再大幅转回来的来回振荡。
当这套模型运行稳定后,再把目标方向替换成寻路系统提供的局部方向,就能形成“路径负责去哪儿,Steering 负责怎么过去”的完整连接。
按自己的节奏,确认真正理解。