在行为树中,需要扩展的主要是行为节点和条件节点。一般来说,每当要创建一个节点时,就要新建一个节点文件。而对于一些简单的行为节点和条件节点,为了去掉新建文件的过程,可以写一个通用版本的行为节点和条件节点,以传入方法的方式来避免新建文件。
BTActionUniversal.lua
1 --[[ 2 通用Action节点 3 --]] 4 BTActionUniversal = BTAction:New(); 5 6 local this = BTActionUniversal; 7 this.name = "BTActionUniversal"; 8 9 function this:New(enterFunc, executeFunc, exitFunc)10 local o = {};11 setmetatable(o, self);12 self.__index = self;13 o.enterFunc = enterFunc;14 o.executeFunc = executeFunc;15 o.exitFunc = exitFunc;16 return o;17 end18 19 function this:Enter()20 if (self.enterFunc) then21 self.enterFunc();22 end23 end24 25 function this:Execute()26 if (self.executeFunc) then27 return self.executeFunc();28 else29 return BTTaskStatus.Failure;30 end31 end32 33 function this:Exit()34 if (self.exitFunc) then35 self.exitFunc();36 end37 end
BTConditionalUniversal.lua
1 --[[ 2 通用Conditional节点 3 --]] 4 BTConditionalUniversal = BTConditional:New(); 5 6 local this = BTConditionalUniversal; 7 this.name = "BTConditionalUniversal"; 8 9 function this:New(checkFunc)10 local o = {};11 setmetatable(o, self);12 self.__index = self;13 o.checkFunc = checkFunc;14 return o;15 end16 17 function this:Check()18 return self.checkFunc(); 19 end
TestBehaviorTree.lua
1 TestBehaviorTree = BTBehaviorTree:New(); 2 3 local this = TestBehaviorTree; 4 this.name = "TestBehaviorTree"; 5 6 function this:New() 7 local o = {}; 8 setmetatable(o, self); 9 self.__index = self;10 o:Init();11 return o;12 end13 14 function this:Init()15 local sequence = BTSequence:New();16 local conditional = self:GetBTConditionalUniversal();17 local action = self:GetBTActionUniversal();18 local log = BTLog:New("This is log!!!");19 log.name = "log";20 21 self:SetStartTask(sequence);22 23 sequence:AddChild(conditional);24 sequence:AddChild(action);25 sequence:AddChild(log);26 end27 28 function this:GetBTConditionalUniversal()29 local a = function ()30 return (2 > 1);31 end32 local universal = BTConditionalUniversal:New(a);33 return universal;34 end35 36 function this:GetBTActionUniversal()37 local count = 1;38 local a = function () print("11"); end39 local b = function ()40 if (count < 3) then41 count = count + 1;42 print("22");43 return BTTaskStatus.Running;44 else45 return BTTaskStatus.Success;46 end47 end48 local c = function () print("33"); end49 local universal = BTActionUniversal:New(a, b, c);50 return universal;51 end
打印如下:
posted on 2018-09-16 19:32 阅读( ...) 评论( ...) 收藏