游戏 AI / 系统课时
用 Seek 让单位追向目标
用 Seek 让单位追向目标
Seek 不只是“朝目标移动”,而是先算出理想速度,再根据单位当前速度求出需要施加的转向力。这样单位不会直接瞬间改变运动状态,而是通过持续加速逐渐追向目标,为后续的 Arrive、Flee 和组合行为打下基础。
学习目标
- 理解目标方向、期望速度与转向力之间的关系。
- 实现带最大速度和最大转向力限制的 Seek。
- 判断 Seek 为什么可能冲过目标,以及哪些参数会影响追踪效果。
Seek 实际在控制什么
假设单位当前位置为 position,当前速度为 velocity,目标位置为 target。第一步不是直接修改位置,而是计算从单位指向目标的方向:target - position。
把方向归一化后乘以 maxSpeed,得到单位此刻最希望拥有的期望速度 desiredVelocity。再用期望速度减去当前速度,才得到真正需要施加的转向量 steering。
可以把核心关系记成三步:目标位置决定往哪里走,最大速度决定希望走多快,当前速度与期望速度的差决定应该怎样转向和加速。

实现一个可运行的 Seek
下面使用普通 Java 实现二维向量和 Seek,不依赖具体游戏引擎。示例把单位质量视为 1,因此转向力可以直接作为加速度使用;真实系统如果包含质量,应先计算 acceleration = steering / mass。
import java.util.Locale;
public class SeekDemo {
static final class Vec2 {
final double x;
final double y;
Vec2(double x, double y) {
this.x = x;
this.y = y;
}
Vec2 add(Vec2 other) {
return new Vec2(x + other.x, y + other.y);
}
Vec2 sub(Vec2 other) {
return new Vec2(x - other.x, y - other.y);
}
Vec2 scale(double value) {
return new Vec2(x * value, y * value);
}
double length() {
return Math.sqrt(x * x + y * y);
}
Vec2 normalized() {
double len = length();
return len < 1e-9 ? new Vec2(0, 0) : scale(1.0 / len);
}
Vec2 limit(double maxLength) {
double len = length();
return len > maxLength ? scale(maxLength / len) : this;
}
}
static Vec2 seek(Vec2 position, Vec2 velocity, Vec2 target,
double maxSpeed, double maxForce) {
// 先得到目标方向对应的理想速度,再修正当前速度。
Vec2 desiredVelocity = target.sub(position)
.normalized()
.scale(maxSpeed);
return desiredVelocity.sub(velocity).limit(maxForce);
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Vec2 position = new Vec2(0, 0);
Vec2 velocity = new Vec2(1, 0);
Vec2 target = new Vec2(10, 5);
double dt = 0.5;
Vec2 steering = seek(position, velocity, target, 4.0, 2.0);
Vec2 nextVelocity = velocity.add(steering.scale(dt)).limit(4.0);
Vec2 nextPosition = position.add(nextVelocity.scale(dt));
System.out.printf("steering=(%.3f, %.3f)%n", steering.x, steering.y);
System.out.printf("velocity=(%.3f, %.3f)%n", nextVelocity.x, nextVelocity.y);
System.out.printf("position=(%.3f, %.3f)%n", nextPosition.x, nextPosition.y);
}
}预期输出:
steering=(1.643, 1.140)
velocity=(1.822, 0.570)
position=(0.911, 0.285)这里没有把单位直接传送到目标,而是先改变速度,再通过速度更新位置。实际游戏循环会每帧重复这一过程,所以运动轨迹由连续的小幅修正组成。
限制速度和转向力
如果只限制 maxSpeed 而不限制 maxForce,单位可能在一帧内猛烈改变速度,看起来像突然拐弯。反过来,如果 maxForce 太小,单位虽然方向正确,却可能需要很长距离才能调整到新的运动方向。
调参时可以分别观察两个现象:直线追踪过快主要调整 maxSpeed;转弯太生硬或跟不上目标,则主要调整 maxForce。帧率变化较大的系统还必须使用真实的 dt 更新速度和位置,不能把每帧持续时间假定为固定值。
Seek 为什么会冲过目标
基础 Seek 始终尝试以 maxSpeed 朝目标运动,即使单位已经非常接近目标,也不会主动减速。因此目标静止时,单位可能高速越过目标,再掉头继续追,形成来回摆动。
这不是实现错误,而是 Seek 的行为定义决定的结果。需要“到达后停稳”时,应在接近目标后逐渐降低期望速度,也就是使用 Arrive 一类行为;需要持续追逐移动目标时,基础 Seek 则非常适合作为最小追踪行为。