[Unity插件]Lua行为树(十):通用行为和通用条件节点

时间:2023-04-19 08:16:26

在行为树中,需要扩展的主要是行为节点和条件节点。一般来说,每当要创建一个节点时,就要新建一个节点文件。而对于一些简单的行为节点和条件节点,为了去掉新建文件的过程,可以写一个通用版本的行为节点和条件节点,以传入方法的方式来避免新建文件。

BTActionUniversal.lua

 --[[
通用Action节点
--]]
BTActionUniversal = BTAction:New(); local this = BTActionUniversal;
this.name = "BTActionUniversal"; function this:New(enterFunc, executeFunc, exitFunc)
local o = {};
setmetatable(o, self);
self.__index = self;
o.enterFunc = enterFunc;
o.executeFunc = executeFunc;
o.exitFunc = exitFunc;
return o;
end function this:Enter()
if (self.enterFunc) then
self.enterFunc();
end
end function this:Execute()
if (self.executeFunc) then
return self.executeFunc();
else
return BTTaskStatus.Failure;
end
end function this:Exit()
if (self.exitFunc) then
self.exitFunc();
end
end

BTConditionalUniversal.lua

 --[[
通用Conditional节点
--]]
BTConditionalUniversal = BTConditional:New(); local this = BTConditionalUniversal;
this.name = "BTConditionalUniversal"; function this:New(checkFunc)
local o = {};
setmetatable(o, self);
self.__index = self;
o.checkFunc = checkFunc;
return o;
end function this:Check()
return self.checkFunc();
end

TestBehaviorTree.lua

 TestBehaviorTree = BTBehaviorTree:New();

 local this = TestBehaviorTree;
this.name = "TestBehaviorTree"; function this:New()
local o = {};
setmetatable(o, self);
self.__index = self;
o:Init();
return o;
end function this:Init()
local sequence = BTSequence:New();
local conditional = self:GetBTConditionalUniversal();
local action = self:GetBTActionUniversal();
local log = BTLog:New("This is log!!!");
log.name = "log"; self:SetStartTask(sequence); sequence:AddChild(conditional);
sequence:AddChild(action);
sequence:AddChild(log);
end function this:GetBTConditionalUniversal()
local a = function ()
return ( > );
end
local universal = BTConditionalUniversal:New(a);
return universal;
end function this:GetBTActionUniversal()
local count = ;
local a = function () print(""); end
local b = function ()
if (count < ) then
count = count + ;
print("");
return BTTaskStatus.Running;
else
return BTTaskStatus.Success;
end
end
local c = function () print(""); end
local universal = BTActionUniversal:New(a, b, c);
return universal;
end

打印如下:

[Unity插件]Lua行为树(十):通用行为和通用条件节点