Files
esengine/packages/behavior-tree/src/BehaviorTreeStarter.ts

180 lines
4.5 KiB
TypeScript
Raw Normal View History

import { Entity } from '@esengine/ecs-framework';
import { BehaviorTreeNode } from './Components/BehaviorTreeNode';
import { ActiveNode } from './Components/ActiveNode';
import { TaskStatus } from './Types/TaskStatus';
/**
* /
*
* 便
*/
export class BehaviorTreeStarter {
/**
*
*
* ActiveNode 使
*
* @param rootEntity
*
* @example
* ```typescript
* const aiRoot = scene.createEntity('aiRoot');
* // ... 构建行为树结构
* BehaviorTreeStarter.start(aiRoot);
* ```
*/
static start(rootEntity: Entity): void {
if (!rootEntity.hasComponent(BehaviorTreeNode)) {
throw new Error('Entity must have BehaviorTreeNode component');
}
if (!rootEntity.hasComponent(ActiveNode)) {
rootEntity.addComponent(new ActiveNode());
}
}
/**
*
*
* ActiveNode
*
* @param rootEntity
*
* @example
* ```typescript
* BehaviorTreeStarter.stop(aiRoot);
* ```
*/
static stop(rootEntity: Entity): void {
this.stopRecursive(rootEntity);
}
/**
*
*/
private static stopRecursive(entity: Entity): void {
// 移除活跃标记
if (entity.hasComponent(ActiveNode)) {
entity.removeComponentByType(ActiveNode);
}
// 重置节点状态
const node = entity.getComponent(BehaviorTreeNode);
if (node) {
node.reset();
}
// 递归处理子节点
for (const child of entity.children) {
this.stopRecursive(child);
}
}
/**
*
*
* ActiveNode
*
* @param rootEntity
*
* @example
* ```typescript
* // 暂停
* BehaviorTreeStarter.pause(aiRoot);
*
* // 恢复
* BehaviorTreeStarter.resume(aiRoot);
* ```
*/
static pause(rootEntity: Entity): void {
this.pauseRecursive(rootEntity);
}
/**
*
*/
private static pauseRecursive(entity: Entity): void {
// 只移除活跃标记,不重置状态
if (entity.hasComponent(ActiveNode)) {
entity.removeComponentByType(ActiveNode);
}
// 递归处理子节点
for (const child of entity.children) {
this.pauseRecursive(child);
}
}
/**
*
*
* ActiveNode
*
* @param rootEntity
*
* @example
* ```typescript
* BehaviorTreeStarter.resume(aiRoot);
* ```
*/
static resume(rootEntity: Entity): void {
this.resumeRecursive(rootEntity);
}
/**
*
*/
private static resumeRecursive(entity: Entity): void {
const node = entity.getComponent(BehaviorTreeNode);
if (!node) {
return;
}
// 如果节点状态是 Running恢复活跃标记
if (node.status === TaskStatus.Running) {
if (!entity.hasComponent(ActiveNode)) {
entity.addComponent(new ActiveNode());
}
}
// 递归处理子节点
for (const child of entity.children) {
this.resumeRecursive(child);
}
}
/**
*
*
*
*
* @param rootEntity
*
* @example
* ```typescript
* BehaviorTreeStarter.restart(aiRoot);
* ```
*/
static restart(rootEntity: Entity): void {
this.stop(rootEntity);
this.start(rootEntity);
}
/**
*
*
* @param rootEntity
* @returns
*
* @example
* ```typescript
* if (BehaviorTreeStarter.isRunning(aiRoot)) {
* console.log('AI is active');
* }
* ```
*/
static isRunning(rootEntity: Entity): boolean {
return rootEntity.hasComponent(ActiveNode);
}
}