Advanced Usage
Performance Optimization
Section titled “Performance Optimization”Tick Rate Control
Section titled “Tick Rate Control”// Reduce update frequency for distant entitiesconst runtime = entity.getComponent(BehaviorTreeRuntimeComponent);runtime.tickInterval = 100; // Update every 100ms instead of every frameConditional Execution
Section titled “Conditional Execution”// Skip execution based on conditionsclass OptimizedSystem extends BehaviorTreeExecutionSystem { shouldProcess(entity: Entity): boolean { const distance = getDistanceToPlayer(entity); return distance < 1000; // Only process nearby entities }}Node Pooling
Section titled “Node Pooling”The framework automatically pools node execution contexts to reduce GC pressure.
Debugging
Section titled “Debugging”Runtime Inspection
Section titled “Runtime Inspection”const runtime = entity.getComponent(BehaviorTreeRuntimeComponent);
// Current stateconsole.log('State:', runtime.state);console.log('Current node:', runtime.currentNodeId);
// Blackboardconsole.log('Health:', runtime.getBlackboardValue('health'));
// Execution historyconsole.log('Last nodes:', runtime.executionHistory);Event Logging
Section titled “Event Logging”runtime.onNodeEnter = (nodeId) => { console.log(`Entering: ${nodeId}`);};
runtime.onNodeExit = (nodeId, status) => { console.log(`Exiting: ${nodeId} with ${status}`);};Visual Debugging
Section titled “Visual Debugging”// Enable visual debuggingruntime.debug = true;
// Draw current execution pathBehaviorTreeDebugger.draw(entity);State Persistence
Section titled “State Persistence”Save State
Section titled “Save State”const state = runtime.serialize();localStorage.setItem('ai-state', JSON.stringify(state));Restore State
Section titled “Restore State”const state = JSON.parse(localStorage.getItem('ai-state'));runtime.deserialize(state);Multi-Tree Entities
Section titled “Multi-Tree Entities”// An entity can have multiple behavior treesconst combatAI = BehaviorTreeBuilder.create('Combat').build();const dialogAI = BehaviorTreeBuilder.create('Dialog').build();
// Start bothBehaviorTreeStarter.start(entity, combatAI, 'combat');BehaviorTreeStarter.start(entity, dialogAI, 'dialog');
// Control individuallyconst combatRuntime = entity.getComponent(BehaviorTreeRuntimeComponent, 'combat');combatRuntime.pause();Custom Execution
Section titled “Custom Execution”Override the default execution system:
class CustomExecutionSystem extends BehaviorTreeExecutionSystem { protected processEntity(entity: Entity, dt: number): void { // Custom pre-processing this.updateBlackboard(entity);
// Standard execution super.processEntity(entity, dt);
// Custom post-processing this.handleResults(entity); }}