SysBehaviorTree.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /** @format */
  2. import {ComBehaviorTree} from '../components/ComBehaviorTree'
  3. import {ECSSystem} from '../lib/ECSSystem'
  4. import {BT} from '../../behaviorTree/BehaviorTree'
  5. import {FightWorld} from '../worlds/FightWorld'
  6. import {ComCocosNode} from '../components/ComCocosNode'
  7. import {GenFilterKey} from '../lib/ECSComponent'
  8. import {Log} from '../../utils/LogUtils'
  9. const FILTER_BEHAVIORTREE = GenFilterKey([ComBehaviorTree, ComCocosNode])
  10. export class SysBehaviorTree extends ECSSystem {
  11. private _context: BT.ExecuteContext
  12. /** 连接 */
  13. public onAdd(world: FightWorld): void {
  14. this._context = new BT.ExecuteContext()
  15. this._context.init(this, world)
  16. }
  17. /** 断开连接 */
  18. public onRemove(world: FightWorld): void {}
  19. /** 添加实体 */
  20. public onEntityEnter(world: FightWorld, entity: number): void {}
  21. /** */
  22. public onEntityLeave(world: FightWorld, entity: number): void {}
  23. /** 更新 */
  24. public onUpdate(world: FightWorld, dt: number): void {
  25. this._context.dt = dt
  26. world.getFilter(FILTER_BEHAVIORTREE).walk((entity: number) => {
  27. let comBehavior = world.getComponent(entity, ComBehaviorTree)
  28. if (!comBehavior.root) return
  29. this._context.set(entity, dt, comBehavior.bb)
  30. if (comBehavior.root.state !== BT.NodeState.Executing) {
  31. this.onEnterBTNode(comBehavior.root, this._context)
  32. } else {
  33. this.updateBTNode(comBehavior.root, this._context)
  34. }
  35. return false
  36. })
  37. }
  38. /** 进入节点 */
  39. public onEnterBTNode(node: BT.NodeBase, context: BT.ExecuteContext) {
  40. let handler = BT.NodeHandlers[node.type]
  41. handler.onEnter(node, context)
  42. }
  43. /** 更新节点状态 */
  44. public updateBTNode(node: BT.NodeBase, context: BT.ExecuteContext) {
  45. let handler = BT.NodeHandlers[node.type]
  46. handler.onUpdate(node, context)
  47. }
  48. public canExecuteBTNode(node: BT.NodeBase, context: BT.ExecuteContext): boolean {
  49. return true
  50. }
  51. }