游戏 AI / 系统课时
路径点怎样驱动角色移动
路径点怎样驱动角色移动
A* 输出的是一串从起点通往终点的路径点,它本身不会让角色移动。本节把搜索结果接入移动循环:维护当前路径点索引,每帧朝目标点推进,进入到达半径后切换下一个点,直到最后一个点被消费完毕。
学习目标
- 理解路径结果与角色移动之间的职责边界
- 实现按顺序消费路径点并推进角色位置
- 正确处理起点重复、到达半径和最终到达状态
路径需要被逐点消费
假设 A* 返回 P0 -> P1 -> P2 -> P3。移动系统不应该每帧重新计算“该走哪个点”,而是保存一个 waypointIndex:当前点到达后索引加一,下一帧自然开始追踪下一个点。
很多路径会把角色当前所在格中心作为第一个节点,因此开始移动前还要允许连续跳过已经到达的点。否则角色可能先试图回到自己的起点中心,再开始向前移动。

每帧只处理当前目标点
移动一步通常需要三个量:当前位置、当前路径点和本帧最大移动距离。设移动速度为 speed,帧间隔为 deltaTime,则本帧最大移动距离是 speed * deltaTime。如果剩余距离小于这个值,应直接落在目标点上,而不是越过目标后下一帧再折返。
到达判断也不宜要求浮点坐标完全相等。实际游戏通常设置一个较小的 arrivalRadius,距离进入该范围就认为当前点已经完成。
下面是一个完整的 C# 控制台示例。它消费三个二维路径点,并以固定速度模拟角色移动。
using System;
using System.Collections.Generic;
using System.Numerics;
public sealed class PathFollower
{
private readonly IReadOnlyList<Vector2> path;
private readonly float speed;
private readonly float arrivalRadius;
private int waypointIndex;
public Vector2 Position { get; private set; }
public bool Arrived => waypointIndex >= path.Count;
public PathFollower(Vector2 start, IReadOnlyList<Vector2> path,
float speed, float arrivalRadius)
{
Position = start;
this.path = path;
this.speed = speed;
this.arrivalRadius = arrivalRadius;
}
public void Tick(float deltaTime)
{
SkipReachedWaypoints();
if (Arrived)
return;
Vector2 target = path[waypointIndex];
Vector2 offset = target - Position;
float distance = offset.Length();
float maxMove = speed * deltaTime;
// 防止一步跨过当前路径点后又折返。
Position = distance <= maxMove
? target
: Position + Vector2.Normalize(offset) * maxMove;
SkipReachedWaypoints();
}
private void SkipReachedWaypoints()
{
while (waypointIndex < path.Count &&
Vector2.Distance(Position, path[waypointIndex]) <= arrivalRadius)
{
Console.WriteLine($"Reached waypoint {waypointIndex}");
waypointIndex++;
}
}
}
public static class Program
{
public static void Main()
{
var path = new List<Vector2>
{
new(0, 0),
new(2, 0),
new(2, 2)
};
var follower = new PathFollower(
start: new Vector2(0, 0),
path: path,
speed: 2f,
arrivalRadius: 0.01f);
while (!follower.Arrived)
follower.Tick(0.5f);
Console.WriteLine($"ARRIVED at ({follower.Position.X:0}, {follower.Position.Y:0})");
}
}预期输出:
Reached waypoint 0
Reached waypoint 1
Reached waypoint 2
ARRIVED at (2, 2)waypoint 0 在第一次更新时直接被跳过,因为角色初始位置已经位于 (0, 0)。随后角色每秒移动 2 个单位,按顺序前往剩余节点。
搜索结果和移动状态不要混在一起
A* 的职责是回答“从哪里经过”,移动组件负责回答“这一帧走多远”。因此移动组件可以读取路径点,却不应该修改 A* 节点的 g、h、父节点等搜索状态;下一次重新规划时,也应把新路径作为新的输入交给移动组件。
路径索引同样属于移动状态。收到一条新路径后应把索引重新定位到路径开头,并重新跳过当前位置已经覆盖的节点。如果直接沿用上一条路径的索引,新路径长度较短时甚至可能立即被误判为已经到达。
转弯处不要只看最终终点
如果角色始终直接朝最终终点移动,那么 A* 中间生成的绕障节点就失去了意义,角色可能直接穿过墙体。正确做法是把当前路径点作为短期目标,只有进入其到达半径后才消费下一个点。
实际移动系统还可以在保持这一消费模型的前提下增加转向平滑、加减速或路径简化。无论视觉运动怎样优化,路径点索引都应保持单调向前;一旦路径因动态障碍失效,则停止消费旧路径并交给重规划逻辑生成新的路径序列。