在 Cocos Creator 中构建 NPC AI,并不是简单实现"会动、会说话"的脚本逻辑,而是一个典型的分层控制系统设计问题。一个可维护、可扩展的 NPC AI 架构,核心在于将"感知、记忆、决策、执行"进行明确拆分,并通过中间抽象层实现解耦,从而保证系统在复杂度增长时依然可控。
以下从工程落地角度,系统说明一套适用于 Cocos Creator 的 NPC AI 架构实现。
一、架构设计原则
在游戏运行时,NPC 不应该直接根据输入做出行为,而应该遵循一个标准的决策链路:
感知输入 → 状态更新 → 决策输出 → 行为执行 → 表现层驱动
这里的关键点在于两点:
第一,AI 只负责"做决定",不直接操作节点
第二,所有行为必须经过约束层过滤
基于此,可以构建如下分层结构:
- 感知层(Perception)
- 记忆层(Memory)
- 决策层(Decision)
- 意图层(Intent)
- 行为层(Action)
- 表现层(View)
这种结构在 Cocos Creator 中可以通过组件组合实现,而不是单一脚本膨胀。
二、NPC 控制器设计
在工程中,建议为每个 NPC 提供一个统一入口组件,作为 AI 的调度中心。
tsx
@ccclass('NpcController')
export class NpcController extends Component {
private perception: PerceptionSystem;
private memory: MemorySystem;
private decision: DecisionSystem;
private action: ActionSystem;
onLoad() {
this.perception = new PerceptionSystem(this.node);
this.memory = new MemorySystem();
this.decision = new DecisionSystem();
this.action = new ActionSystem(this.node);
}
update(dt: number) {
const input = this.perception.collect();
this.memory.update(input);
const intent = this.decision.think(this.memory.getSnapshot());
const action = this.action.resolve(intent);
this.action.execute(action);
}
}
这个组件本身不包含具体 AI 逻辑,仅负责调度各个子系统,从而保证职责单一。
三、感知系统设计
感知系统用于限定 NPC 的信息来源,是 AI 边界的第一层。
在实际实现中,应避免 NPC 直接访问全局数据,而是通过过滤机制获取"可见信息"。常见过滤条件包括距离、类型和事件触发。
tsx
export class PerceptionSystem {
constructor(private owner: Node) {}
collect() {
const result = [];
const entities = getSceneEntities();
for (let e of entities) {
const dist = Vec3.distance(this.owner.worldPosition, e.worldPosition);
if (dist < 10) {
result.push(e);
}
}
return result;
}
}
这种设计确保 NPC 不具备全局视角,从而避免"全知行为"。
四、记忆系统设计
记忆系统用于管理 NPC 的历史信息与当前状态,是决策的基础数据源。
推荐采用分层结构:
- 短期记忆,用于存储最近发生的事件
- 长期记忆,用于存储关键事实
- 状态信息,用于描述当前行为阶段
tsx
interface MemorySnapshot {
shortTerm: any[];
longTerm: Map<string, any>;
state: string;
}
export class MemorySystem {
private shortTerm: any[] = [];
private longTerm = new Map<string, any>();
private state: string = "idle";
update(inputs: any[]) {
this.shortTerm.push(...inputs);
if (this.shortTerm.length > 10) {
this.shortTerm.shift();
}
}
getSnapshot(): MemorySnapshot {
return {
shortTerm: this.shortTerm,
longTerm: this.longTerm,
state: this.state
};
}
}
通过限制短期记忆容量,可以有效控制性能与信息噪声。
五、决策系统设计
决策系统是 AI 的核心模块,其职责是将当前记忆转化为"意图"。
在工程中,推荐优先使用有限状态机作为基础实现方式,因为其具备稳定性强、可预测性高的特点。
tsx
export class DecisionSystem {
think(memory: MemorySnapshot): string {
if (memory.state === "idle") {
if (this.hasEnemy(memory)) {
return "enter_combat";
}
return "patrol";
}
if (memory.state === "combat") {
return "attack";
}
return "idle";
}
private hasEnemy(memory: MemorySnapshot): boolean {
return memory.shortTerm.some(e => e.type === "enemy");
}
}
对于复杂项目,可以在此基础上引入行为树,但不建议直接用大模型替代所有决策逻辑。若使用大模型,应仅输出高层意图,并保留规则系统作为约束。
六、意图层设计
意图层是连接 AI 与行为系统的关键抽象层。
其作用是将复杂决策统一映射为有限集合,从而保证系统稳定性。
tsx
type Intent =
| "idle"
| "patrol"
| "attack"
| "flee"
| "talk";
通过限制意图空间,可以避免 AI 输出不可控行为。
七、行为系统设计
行为系统负责将意图转换为具体执行逻辑,并与 Cocos 的组件系统对接。
tsx
export class ActionSystem {
constructor(private node: Node) {}
resolve(intent: string): string {
if (!this.isValid(intent)) {
return "idle";
}
return intent;
}
execute(action: string) {
switch (action) {
case "patrol":
this.patrol();
break;
case "attack":
this.attack();
break;
case "idle":
this.idle();
break;
}
}
private isValid(action: string) {
return ["patrol", "attack", "idle"].includes(action);
}
private attack() {
const anim = this.node.getComponent(Animation);
anim?.play("attack");
}
private patrol() {
// 移动逻辑
}
private idle() {
// 待机逻辑
}
}
这一层必须具备"白名单"机制,确保任何非法行为都被拦截。
八、状态约束机制
为了防止 AI 输出与当前状态冲突,需要引入额外的状态约束层。
例如:
tsx
if (memory.state !== "combat" && intent === "attack") {
intent = "idle";
}
该机制可以防止 NPC 在不合理场景下执行动作,例如在对话中发起攻击。
九、与 Cocos Creator 的结合
在实际项目中,AI 系统需要与引擎组件协同工作,包括:
- Animation 控制动画播放
- Node 控制位移与层级
- EventSystem 处理交互事件
- Prefab 实现数据复用
推荐将 AI 逻辑与表现层完全分离,即 AI 不直接修改节点属性,而是通过 ActionSystem 调用接口。
十、性能与调度优化
在多 NPC 场景中,AI 系统很容易成为性能瓶颈,需要进行调度控制。
首先,应避免每帧执行决策逻辑,可以采用降频更新策略。
tsx
private timer = 0;
update(dt: number) {
this.timer += dt;
if (this.timer < 0.5) return;
this.timer = 0;
this.tickAI();
}
其次,可以采用分帧调度,将 NPC 分组执行,从而平摊计算压力。
十一、总结
在 Cocos Creator 中实现 NPC AI,本质上是一个分层控制系统的工程实践问题。关键不在于算法复杂度,而在于结构设计是否清晰。