AI

来源:互联网 发布:数据库原理王珊答案 编辑:程序博客网 时间:2024/04/26 04:36

查阅了一些行为树资料,目前最主要是参考了这篇文章,看完后感觉行为树实乃强大,绝对是替代状态机的不二之选。但从理论看起来很简单的行为树,真正着手起来却发现很多细节无从下手。


总结起来,就是:

1、行为树只是单纯的一棵决策树,还是决策+控制树。为了防止不必要的麻烦,我目前设计成单纯的决策树。

2、什么时候执行行为树的问题,也就是行为树的Tick问题,是在条件变化的时候执行一次,还是只要对象激活,就在Update里面一直Tick。前者明显很节省开销,但那样设计的最终结果可能是最后陷入事件发送的泥潭中。那么一直Tick可能是最简单的办法,于是就引下面出新的问题。目前采用了一直Tick的办法。

3、基本上可以明显节点有 Composite Node、Decorator Node、Condition Node、Action Node,但具体细节就很头疼。比如组合节点里的Sequence Node。这个节点是不是在每个Tick周期都从头迭代一次子节点,还是记录正在运行的子节点。每次都迭代子节点,就感觉开销有点大。记录运行节点就会出现条件冗余问题,具体后面再讨论。目前采用保存当前运行节点的办法。

4、条件节点(Condition Node)的位置问题。看到很多设计都是条件节点在最后才进行判断,而实际上,如果把条件放在组合节点处,就可以有效短路判断,不再往下迭代。于是我就采用了这种方法。


设计开始

在Google Code上看到的某个行为树框架,用的是抽象类做节点。考虑到C#不能多继承,抽象类可能会导致某些时候会很棘手,所以还是用接口。虽然目前还未发现接口的好处。

在进行抽象设计的时候,接口的纯粹性虽然看起来更加清晰,不过有时候遇到需要重复使用某些类函数的时候就挺麻烦,让人感觉有点不利于复用。

[csharp] view plain copy
  1. public enum RunStatus  
  2. {  
  3.     Completed,  
  4.     Failure,  
  5.     Running,  
  6. }  
  7.   
  8. public interface IBehaviourTreeNode  
  9. {  
  10.     RunStatus status { getset; }  
  11.     string nodeName { getset; }  
  12.     bool Enter(object input);  
  13.     bool Leave(object input);  
  14.     bool Tick(object input, object output);  
  15.     RenderableNode renderNode { getset; }  
  16.     IBehaviourTreeNode parent { getset; }  
  17.     IBehaviourTreeNode Clone();  
  18. }  
  19.   
  20. /************************************************************************/  
  21. /* 组合结点                                                             */  
  22. /************************************************************************/  
  23. public interface ICompositeNode : IBehaviourTreeNode  
  24. {  
  25.     void AddNode(IBehaviourTreeNode node);  
  26.     void RemoveNode(IBehaviourTreeNode node);  
  27.     bool HasNode(IBehaviourTreeNode node);  
  28.   
  29.     void AddCondition(IConditionNode node);  
  30.     void RemoveCondition(IConditionNode node);  
  31.     bool HasCondition(IConditionNode node);  
  32.   
  33.     ArrayList nodeList { get; }  
  34.     ArrayList conditionList { get; }  
  35. }  
  36.   
  37. /************************************************************************/  
  38. /* 选择节点                                                             */  
  39. /************************************************************************/  
  40. public interface ISelectorNode : ICompositeNode  
  41. {  
  42.   
  43. }  
  44.   
  45. /************************************************************************/  
  46. /*顺序节点                                                              */  
  47. /************************************************************************/  
  48. public interface ISequenceNode : ICompositeNode  
  49. {  
  50.   
  51. }  
  52.   
  53. /************************************************************************/  
  54. /* 平行(并列)节点                                                             */  
  55. /************************************************************************/  
  56. public interface IParallelNode : ICompositeNode  
  57. {  
  58.   
  59. }  
  60.   
  61. //////////////////////////////////////////////////////////////////////////  
  62.   
  63. /************************************************************************/  
  64. /* 装饰结点                                                             */  
  65. /************************************************************************/  
  66. public interface IDecoratorNode : IBehaviourTreeNode  
  67. {  
  68.   
  69. }  
  70.   
  71. /************************************************************************/  
  72. /* 条件节点                                                             */  
  73. /************************************************************************/  
  74. public interface IConditionNode  
  75. {  
  76.     string nodeName { getset; }  
  77.     bool ExternalCondition();  
  78. }  
  79.   
  80. /************************************************************************/  
  81. /* 行为节点                                                             */  
  82. /************************************************************************/  
  83. public interface IActionNode : IBehaviourTreeNode  
  84. {  
  85.   
  86. }  
  87.   
  88. public interface IBehaviourTree  
  89. {  
  90.       
  91. }  

很多节点的接口都是空的,目前唯一的作用就是用于类型判断,很可能在最后也没有什么实际的作用,搞不好就是所谓的过度设计。如果最终确定没有用再删掉吧。

接口里出现了一个渲染节点,目的是为了能够更方便的把这个节点和负责渲染的节点联系到一起,方便节点的可视化。


如果只有接口,每次实现接口都要重复做很多工作,为了利用面向对象的复用特性,就来实现一些父类


[csharp] view plain copy
  1. public class BaseNode  
  2. {  
  3.     public BaseNode() { nodeName_ = this.GetType().Name + "\n"; }  
  4.   
  5.     protected RunStatus status_ = RunStatus.Completed;  
  6.     protected string nodeName_;  
  7.     protected RenderableNode renderNode_;  
  8.     protected IBehaviourTreeNode parent_;  
  9.   
  10.     public virtual RunStatus status { get { return status_; } set { status_ = value; } }  
  11.     public virtual string nodeName { get { return nodeName_; } set { nodeName_ = value; } }  
  12.     public virtual RenderableNode renderNode { get { return renderNode_; } set { renderNode_ = value; } }  
  13.     public virtual IBehaviourTreeNode parent { get { return parent_; } set { parent_ = value; } }  
  14.     public virtual IBehaviourTreeNode Clone() {  
  15.         var clone = new BaseNode();  
  16.         clone.status_ = status_;  
  17.         clone.nodeName_ = nodeName_;  
  18.         clone.renderNode_ = renderNode_;  
  19.         clone.parent_ = parent_;  
  20.         return clone as IBehaviourTreeNode;  
  21.     }  
  22. }  
  23.   
  24. public class BaseActionNode : IActionNode  
  25. {  
  26.     public BaseActionNode() { nodeName_ = this.GetType().Name + "\n"; }  
  27.     protected RunStatus status_ = RunStatus.Completed;  
  28.     protected string nodeName_;  
  29.     protected RenderableNode renderNode_;  
  30.     protected IBehaviourTreeNode parent_;  
  31.     public virtual RunStatus status { get { return status_; } set { status_ = value; } }  
  32.     public virtual string nodeName { get { return nodeName_; } set { nodeName_ = value; } }  
  33.     public virtual RenderableNode renderNode { get { return renderNode_; } set { renderNode_ = value; } }  
  34.     public virtual IBehaviourTreeNode parent { get { return parent_; } set { parent_ = value; } }  
  35.     public virtual IBehaviourTreeNode Clone()  
  36.     {  
  37.         var clone = new BaseActionNode();  
  38.         clone.status_ = status_;  
  39.         clone.nodeName_ = nodeName_;  
  40.         clone.renderNode_ = renderNode_;  
  41.         clone.parent_ = parent_;  
  42.         return clone as IBehaviourTreeNode;  
  43.     }  
  44.   
  45.     public virtual bool Enter(object input)  
  46.     {  
  47.         status_ = RunStatus.Running;  
  48.         return true;  
  49.     }  
  50.   
  51.     public virtual bool Leave(object input)  
  52.     {  
  53.         status_ = RunStatus.Completed;  
  54.         return true;  
  55.     }  
  56.   
  57.     public virtual bool Tick(object input, object output)  
  58.     {  
  59.         return true;  
  60.     }  
  61. }  
  62. public class BaseCondictionNode {  
  63.     protected string nodeName_;  
  64.     public virtual string nodeName { get { return nodeName_; } set { nodeName_ = value; } }  
  65.     public BaseCondictionNode() { nodeName_ = this.GetType().Name+"\n"; }  
  66.     public delegate bool ExternalFunc();  
  67.     protected ExternalFunc externalFunc;  
  68.     public static ExternalFunc GetExternalFunc(BaseCondictionNode node) {  
  69.         return node.externalFunc;  
  70.     }  
  71. }  
  72.   
  73. public class Precondition : BaseCondictionNode, IConditionNode{  
  74.     public Precondition(ExternalFunc func) { externalFunc = func; }  
  75.     public Precondition(BaseCondictionNode pre) { externalFunc = BaseCondictionNode.GetExternalFunc(pre); }  
  76.     public bool ExternalCondition()  
  77.     {  
  78.         if (externalFunc != nullreturn externalFunc();  
  79.         else return false;  
  80.     }  
  81. }  
  82.   
  83. public class PreconditionNOT : BaseCondictionNode, IConditionNode  
  84. {  
  85.     public PreconditionNOT(ExternalFunc func) { externalFunc = func; }  
  86.     public PreconditionNOT(BaseCondictionNode pre) { externalFunc = BaseCondictionNode.GetExternalFunc(pre); }  
  87.     public bool ExternalCondition()  
  88.     {  
  89.         if (externalFunc != nullreturn !externalFunc();  
  90.         else return false;  
  91.     }  
  92. }  
  93.   
  94. public class BaseCompositeNode : BaseNode{  
  95.     protected ArrayList nodeList_ = new ArrayList();  
  96.     protected ArrayList conditionList_ = new ArrayList();  
  97.     protected int runningNodeIndex = 0;  
  98.     protected bool CheckNodeAndCondition() {  
  99.         if (nodeList_.Count == 0)  
  100.         {  
  101.             status_ = RunStatus.Failure;  
  102.             Debug.Log("SequenceNode has no node!");  
  103.             return false;  
  104.         }  
  105.         return CheckCondition();  
  106.     }  
  107.     protected bool CheckCondition() {  
  108.         foreach (var node in conditionList_)  
  109.         {  
  110.             var condiction = node as IConditionNode;  
  111.             if (!condiction.ExternalCondition())  
  112.                 return false;  
  113.         }  
  114.         return true;  
  115.     }  
  116.     public virtual void AddNode(IBehaviourTreeNode node) { node.parent = (IBehaviourTreeNode)this; nodeList_.Add(node); }  
  117.     public virtual void RemoveNode(IBehaviourTreeNode node) { nodeList_.Remove(node); }  
  118.     public virtual bool HasNode(IBehaviourTreeNode node) { return nodeList_.Contains(node); }  
  119.   
  120.     public virtual void AddCondition(IConditionNode node) { conditionList_.Add(node); }  
  121.     public virtual void RemoveCondition(IConditionNode node) { conditionList_.Remove(node); }  
  122.     public virtual bool HasCondition(IConditionNode node) { return conditionList_.Contains(node); }  
  123.   
  124.     public virtual ArrayList nodeList { get { return nodeList_; } }  
  125.     public virtual ArrayList conditionList { get { return conditionList_; } }  
  126.   
  127.     public override IBehaviourTreeNode Clone()  
  128.     {  
  129.         var clone = base.Clone() as BaseCompositeNode;  
  130.         clone.nodeList_.AddRange(nodeList_);  
  131.         clone.conditionList_.AddRange(conditionList_);  
  132.         clone.runningNodeIndex = runningNodeIndex;  
  133.         return clone as IBehaviourTreeNode;  
  134.     }  
  135. }  


然后实现具体的节点,先是序列节点

[csharp] view plain copy
  1. public class SequenceNode : BaseCompositeNode, ISequenceNode  
  2. {  
  3.     public SequenceNode(bool canContinue_ = false) { canContinue = canContinue_; }  
  4.     public bool canContinue = false;  
  5.   
  6.   
  7.     public bool Enter(object input)  
  8.     {  
  9.         var checkOk = CheckNodeAndCondition();  
  10.         if (!checkOk) return false;  
  11.         var runningNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  12.         checkOk = runningNode.Enter(input);  
  13.         if (!checkOk) return false;  
  14.         status_ = RunStatus.Running;  
  15.         return true;  
  16.     }  
  17.   
  18.     public bool Leave(object input)  
  19.     {  
  20.         if (nodeList_.Count == 0)  
  21.         {  
  22.             status_ = RunStatus.Failure;  
  23.             Debug.Log("SequenceNode has no node!");  
  24.             return false;  
  25.         }  
  26.         var runningNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  27.         runningNode.Leave(input);  
  28.         if (canContinue)  
  29.         {  
  30.             runningNodeIndex++;  
  31.             runningNodeIndex %= nodeList_.Count;  
  32.         }  
  33.         status_ = RunStatus.Completed;  
  34.         return true;  
  35.     }  
  36.   
  37.     public bool Tick(object input, object output)  
  38.     {  
  39.         if (status_ == RunStatus.Failure) return false;  
  40.         if (status_ == RunStatus.Completed) return true;  
  41.           
  42.         var runningNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  43.         var checkOk = CheckCondition();  
  44.         if (!checkOk)  
  45.         {  
  46.             return false;  
  47.         }  
  48.   
  49.         switch (runningNode.status)  
  50.         {  
  51.             case RunStatus.Running:  
  52.                 if (!runningNode.Tick(input, output))  
  53.                 {  
  54.                     runningNode.Leave(input);  
  55.                     return false;  
  56.                 }  
  57.   
  58.                 break;  
  59.             default:  
  60.                 runningNode.Leave(input);  
  61.                 runningNodeIndex++;  
  62.                 if(runningNodeIndex >= nodeList_.Count)break;  
  63.                 var nextNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  64.                 var check = nextNode.Enter(input);  
  65.                 if (!check) return false;  
  66.                 break;  
  67.         }  
  68.         return true;  
  69.     }  
  70.   
  71.     public override IBehaviourTreeNode Clone()  
  72.     {  
  73.         var clone = base.Clone() as SequenceNode;  
  74.         clone.canContinue = canContinue;  
  75.         return clone;  
  76.     }  
  77. }  

这就是序列节点的设计,但是明显看起来很不爽,里面还出现了一个别扭的变量canContinue 。为什么会出现这个?因为序列节点的特点就是遇到一个子节点FALSE,就会停止并返回FALSE,但是这里我想用序列节点来做根节点,如果是根节点遇到这种情况,那么就不会执行下一个节点,而我看了很多种对于几大节点的描述,似乎都没提到这个。很多都用序列节点做根节点,有些就直接说是根节点。那么要么根节点另外实现,要么改一下序列节点。因为如果序列节点是非根节点的情况下,如果不是每次都从头开始,似乎又会引来新的问题,虽然目前还没想到会出什么问题。不过最后实现执行起来之后发现,用选择节点其实是一样的。所以目前这样的设计,可能是有根本上的问题。希望哪位大神可以指点一下。


然后是选择节点,根据了所有FALSE才返回FALSE的特点设计了


[csharp] view plain copy
  1. public class SelectorNode : BaseCompositeNode, ISelectorNode  
  2. {  
  3.     public bool Enter(object input)  
  4.     {  
  5.         var checkOk = CheckNodeAndCondition();  
  6.         if (!checkOk) return false;  
  7.          
  8.         do  
  9.         {  
  10.             var runningNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  11.             checkOk = runningNode.Enter(input);  
  12.             if (checkOk) break;  
  13.             runningNodeIndex++;  
  14.             if (runningNodeIndex >= nodeList_.Count) return false;  
  15.         } while (!checkOk);  
  16.           
  17.         status_ = RunStatus.Running;  
  18.         return true;  
  19.     }  
  20.   
  21.     public bool Leave(object input)  
  22.     {  
  23.         var runningNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  24.         runningNode.Leave(input);  
  25.         runningNodeIndex = 0;  
  26.         status_ = RunStatus.Completed;  
  27.         return true;  
  28.     }  
  29.   
  30.     public bool Tick(object input, object output)  
  31.     {  
  32.         if (status_ == RunStatus.Failure) return false;  
  33.         if (status_ == RunStatus.Completed) return true;  
  34.         var checkOk1 = CheckCondition();  
  35.         if (!checkOk1) return false;  
  36.         var runningNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  37.         switch (runningNode.status)  
  38.         {  
  39.             case RunStatus.Running:  
  40.                 if (!runningNode.Tick(input, output))  
  41.                 {  
  42.                     runningNode.Leave(input);  
  43.                     return false;  
  44.                 }  
  45.   
  46.                 break;  
  47.             default:  
  48.                 runningNode.Leave(input);  
  49.                 runningNodeIndex++;  
  50.                 if (runningNodeIndex >= nodeList_.Count) return false;  
  51.   
  52.                 bool checkOk = false;  
  53.                 do  
  54.                 {  
  55.                     var nextNode = nodeList_[runningNodeIndex] as IBehaviourTreeNode;  
  56.                     checkOk = nextNode.Enter(input);  
  57.                     if (checkOk) break;  
  58.                     runningNodeIndex++;  
  59.                     if (runningNodeIndex >= nodeList_.Count) return false;  
  60.                 } while (!checkOk);  
  61.                 break;  
  62.         }  
  63.         return true;  
  64.     }  
  65. }  

目前对于我的简单DEMO,组合节点只需要这两个就够了,实际上只需要选择节点、条件节点、动作节点就够了。所以说设计是不完全的,虽然能够实现目标需求,但是实际工作量仍挺大,具体接下来会说明。


行为节点



先放一些渲染节点的代码。实际上我基本上是第一次接触自己去渲染一种数据结构,看完网上的大牛们随随便便就能写出个数据结构的示意图,不得不佩服。我一时半会没想出怎么渲染出树状结构,于是就简单的把树按层分组,一层一层渲染,缺点就是不能很好的表现树的样子,父子关系不能很好的表示。这里放出来希望能抛砖引玉。我以后可能会去完事它,但是现在首先是要搞清楚行为树。实现这个完全是为了看看节点是否正确放置,以方便调试。

[csharp] view plain copy
  1. public class RenderableNode  
  2. {  
  3.     public RenderableNode parent;  
  4.     public IBehaviourTreeNode targetNode;  
  5.     public Rect posRect = new Rect();  
  6.     public string name;  
  7.     public int layer;  
  8.     public RunStatus staus;  
  9.     public override string ToString()  
  10.     {  
  11.         return name + "\n" + staus.ToString();  
  12.     }  
  13.     public virtual void Render()  
  14.     {  
  15.         bool running = staus == RunStatus.Running;  
  16.         var rect = posRect;  
  17.         rect.y -= (posRect.height / 2);  
  18.   
  19.         var oldColor = GUI.color;  
  20.          if (running)  
  21.         {  
  22.             GUI.color = Color.green;  
  23.         }  
  24.         GUI.Box(rect, ToString());  
  25.         GUI.color = oldColor;  
  26.   
  27.         if (parent == null && targetNode != null && targetNode.parent!=null)  
  28.         {  
  29.             parent = targetNode.parent.renderNode;  
  30.         }  
  31.         if (parent != null)  
  32.         {  
  33.             Vector2 parentPos = new Vector2();  
  34.             parentPos.x = parent.posRect.x + parent.posRect.width;  
  35.             parentPos.y = parent.posRect.y;  
  36.             GUIHelper.DrawLine(new Vector2(rect.x, rect.y + rect.height / 2), parentPos, running?Color.green:Color.yellow);  
  37.         }  
  38.           
  39.     }  
  40. }  
  41.   
  42. public class RenderableCondictionNode : RenderableNode  
  43. {  
  44.     public IConditionNode targetCondictionNode;  
  45.     public override string ToString() { parent = nullreturn name; }  
  46.     public override void Render()  
  47.     {  
  48.         var rect = posRect;  
  49.         rect.y -= (posRect.height / 2);  
  50.   
  51.         var oldColor = GUI.color;  
  52.         if (targetCondictionNode.ExternalCondition())  
  53.             GUI.color = Color.green;  
  54.         else  
  55.             GUI.color = Color.blue;  
  56.         GUI.Box(rect, ToString());  
  57.         GUI.color = oldColor;  
  58.     }  
  59. }  
  60.   
  61. public class EmptyNode : RenderableNode { public override void Render() { } }  
  62.   
  63. public class NodeBox  
  64. {  
  65.     public Rect posRect = new Rect();  
  66.     public List<RenderableNode> nodeList = new List<RenderableNode>();  
  67.     public void AddNode(RenderableNode node)  
  68.     {  
  69.         nodeList.Add(node);  
  70.     }  
  71.     public void Render()  
  72.     {  
  73.         posRect.y = Screen.height / 2;  
  74.         Rect rect = new Rect();  
  75.   
  76.         foreach (var node in nodeList)  
  77.         {  
  78.             var n = node;  
  79.             rect.height += (n.posRect.height + 1);  
  80.             rect.width = n.posRect.width + 10;  
  81.         }  
  82.         rect.height += 10;  
  83.         rect.x = posRect.x - rect.width / 2;  
  84.         rect.y = posRect.y - rect.height / 2;  
  85.         //GUI.Box(rect, "");  
  86.         posRect.width = rect.width;  
  87.         posRect.height = rect.height;  
  88.         float height = 0;  
  89.         for (var i = 0; i < nodeList.Count; i++)  
  90.         {  
  91.             var n = nodeList[i];  
  92.             n.posRect.y = rect.y + height + n.posRect.height / 2 + 5;  
  93.             n.posRect.x = rect.x + 5;  
  94.             n.Render();  
  95.             height += n.posRect.height + 1;  
  96.         }  
  97.     }  
  98. }  


放一张渲染出来的效果


虽然每一组都只是简单的居中,不过效果看起来还可以接受


然后从图中就可以看到问题了。所有正条件,都会有一个反条件,不这么做就无法在条件改变时,让当前节点返回FALSE,从而让行为树去寻找其他节点。而如果用状态机来做的话,条件肯定只用判断一次,比如

[csharp] view plain copy
  1. if(run){  
  2.    Run();  
  3. }  
  4. else{  
  5.    Walk();  
  6. }  
那么可能就回到最初的组合节点的设计了,组合节点就不得不每次都扫描条件。其实本质上我是在担心开销问题,因为变成节点后,就不在是if else那么简单,而是变成了函数调用的开销。简单的AI还好,如果大量复杂的AI,每次对整棵树进行扫描估计够呛。但是目前的设计,条件节点就会非常多,条件不完备就会出现BUG,似乎也不是非常好的情况。



最后放出一些细节

[csharp] view plain copy
  1. class PatrolAction : BaseActionNode {  
  2.   
  3.         public PatrolAction() { nodeName_ += "巡逻行为"; }  
  4.   
  5.         public override bool Tick(object input_, object output_)  
  6.         {  
  7.            // var input = input_ as WarriorInputData;  
  8.             var output = output_ as WarriorOutPutData;  
  9.             output.action = WarriorActon.ePatrol;  
  10.             return true;  
  11.         }  
  12.     }  
  13.   
  14.     class RunAwayAction : BaseActionNode {  
  15.         public RunAwayAction() { nodeName_ += "逃跑行为"; }  
  16.   
  17.         public override bool Tick(object input_, object output_)  
  18.         {  
  19.             // var input = input_ as WarriorInputData;  
  20.             var output = output_ as WarriorOutPutData;  
  21.             output.action = WarriorActon.eRunAway;  
  22.             return true;  
  23.         }  
  24.     }  
  25.   
  26.     class AttackAction : BaseActionNode {  
  27.         public AttackAction() { nodeName_ += "攻击行为"; }  
  28.   
  29.         public override bool Tick(object input_, object output_)  
  30.         {  
  31.             // var input = input_ as WarriorInputData;  
  32.             var output = output_ as WarriorOutPutData;  
  33.             output.action = WarriorActon.eAttack;  
  34.             return true;  
  35.         }  
  36.     }  
  37.   
  38.     class CrazyAttackAction : BaseActionNode {  
  39.         public CrazyAttackAction() { nodeName_ += "疯狂攻击行为"; }  
  40.   
  41.         public override bool Tick(object input_, object output_)  
  42.         {  
  43.             // var input = input_ as WarriorInputData;  
  44.             var output = output_ as WarriorOutPutData;  
  45.             output.action = WarriorActon.eCrazyAttack;  
  46.             return true;  
  47.         }  
  48.     }  
  49.   
  50.     class AlertAction : BaseActionNode  
  51.     {  
  52.         public AlertAction() { nodeName_ += "警戒行为"; }  
  53.         public override bool Tick(object input_, object output_)  
  54.         {  
  55.             // var input = input_ as WarriorInputData;  
  56.             var output = output_ as WarriorOutPutData;  
  57.             output.action = WarriorActon.eAlert;  
  58.             return true;  
  59.         }  
  60.     }  


[csharp] view plain copy
  1. private ICompositeNode rootNode = new SelectorNode();  
  2.     private WarriorInputData inputData = new WarriorInputData();  
  3.     private WarriorOutPutData outputData = new WarriorOutPutData();  
  4.     // Use this for initialization  
  5.     public void Start()  
  6.     {  
  7.         inputData.attribute = GetComponent<CharacterAttribute>();  
  8.   
  9.         rootNode.nodeName += "根";  
  10.   
  11.         //条件  
  12.         var hasNoTarget = new PreconditionNOT(() => { return inputData.attribute.hasTarget; });  
  13.         hasNoTarget.nodeName = "无目标";  
  14.         var hasTarget = new Precondition(hasNoTarget);  
  15.         hasTarget.nodeName = "发现目标";  
  16.         var isAnger = new Precondition(() => { return inputData.attribute.isAnger; });  
  17.         isAnger.nodeName = "愤怒状态";  
  18.         var isNotAnger = new PreconditionNOT(isAnger);  
  19.         isNotAnger.nodeName = "非愤怒状态";  
  20.         var HPLessThan500 = new Precondition(() => { return inputData.attribute.health < 500; });  
  21.         HPLessThan500.nodeName = "血少于500";  
  22.         var HPMoreThan500 = new PreconditionNOT(HPLessThan500);  
  23.         HPMoreThan500.nodeName = "血大于500";  
  24.         var isAlert = new Precondition(() => { return inputData.attribute.isAlert; });  
  25.         isAlert.nodeName = "警戒";  
  26.         var isNotAlert = new PreconditionNOT(isAlert);  
  27.         isNotAlert.nodeName = "非警戒";  
  28.   
  29.   
  30.         var patrolNode = new SequenceNode();  
  31.         patrolNode.nodeName += "巡逻";  
  32.         patrolNode.AddCondition(hasNoTarget);  
  33.         patrolNode.AddCondition(isNotAlert);  
  34.         patrolNode.AddNode(new PatrolAction());  
  35.   
  36.         var alert = new SequenceNode();  
  37.         alert.nodeName += "警戒";  
  38.         alert.AddCondition(hasNoTarget);  
  39.         alert.AddCondition(isAlert);  
  40.         alert.AddNode(new AlertAction());  
  41.           
  42.         var runaway = new SequenceNode();  
  43.         runaway.nodeName += "逃跑";  
  44.         runaway.AddCondition(hasTarget);  
  45.         runaway.AddCondition(HPLessThan500);  
  46.         runaway.AddNode(new RunAwayAction());  
  47.   
  48.         var attack = new SelectorNode();  
  49.         attack.nodeName += "攻击";  
  50.         attack.AddCondition(hasTarget);  
  51.         attack.AddCondition(HPMoreThan500);  
  52.   
  53.         var attackCrazy = new SequenceNode();  
  54.         attackCrazy.nodeName += "疯狂攻击";  
  55.         attackCrazy.AddCondition(isAnger);  
  56.         attackCrazy.AddNode(new CrazyAttackAction());  
  57.         attack.AddNode(attackCrazy);  
  58.   
  59.         var attackNormal = new SequenceNode();  
  60.         attackNormal.nodeName += "普通攻击";  
  61.         attackNormal.AddCondition(isNotAnger);  
  62.         attackNormal.AddNode(new AttackAction());  
  63.         attack.AddNode(attackNormal);  
  64.   
  65.         rootNode.AddNode(patrolNode);  
  66.         rootNode.AddNode(alert);  
  67.         rootNode.AddNode(runaway);  
  68.         rootNode.AddNode(attack);  
  69.         var ret = rootNode.Enter(inputData);  
  70.         if (!ret)  
  71.         {  
  72.             Debug.Log("无可执行节点!");  
  73.         }  
  74.     }  
  75.       
  76.     // Update is called once per frame  
  77.     void Update () {  
  78.         var ret = rootNode.Tick(inputData, outputData);  
  79.   
  80.         if (!ret)  
  81.             rootNode.Leave(inputData);  
  82.   
  83.         if (rootNode.status == RunStatus.Completed)  
  84.         {  
  85.             ret = rootNode.Enter(inputData);  
  86.             if (!ret)  
  87.                 rootNode.Leave(inputData);  
  88.         }  
  89.         else if (rootNode.status == RunStatus.Failure)  
  90.         {  
  91.             Debug.Log("BT Failed");  
  92.             enabled = false;  
  93.         }  
  94.   
  95.         if (outputData.action != inputData.action)  
  96.         {  
  97.             OnActionChange(outputData.action, inputData.action);  
  98.             inputData.action = outputData.action;  
  99.         }  
  100.     }  
  101.   
  102.     void OnActionChange(WarriorActon action, WarriorActon lastAction) {  
  103.       //  print("OnActionChange "+action+" last:"+lastAction);  
  104.         switch (lastAction)  
  105.         {  
  106.             case WarriorActon.ePatrol:  
  107.                 GetComponent<WarriorPatrol>().enabled = false;  
  108.                 break;  
  109.             case WarriorActon.eAttack:  
  110.             case WarriorActon.eCrazyAttack:  
  111.                 GetComponent<WarriorAttack>().enabled = false;  
  112.                 break;  
  113.             case WarriorActon.eRunAway:  
  114.                 GetComponent<WarriorRunAway>().enabled = false;  
  115.                 break;  
  116.             case WarriorActon.eAlert:  
  117.                 GetComponent<WarriorAlert>().enabled = false;  
  118.                 break;  
  119.         }  
  120.   
  121.         switch (action) {   
  122.             case WarriorActon.ePatrol:  
  123.                 GetComponent<WarriorPatrol>().enabled = true;  
  124.                 break;  
  125.             case WarriorActon.eAttack:  
  126.                 var attack = GetComponent<WarriorAttack>();  
  127.                 attack.revenge = false;  
  128.                 attack.enabled = true;  
  129.                 break;  
  130.             case WarriorActon.eCrazyAttack:  
  131.                 var crazyAttack = GetComponent<WarriorAttack>();  
  132.                 crazyAttack.revenge = true;  
  133.                 crazyAttack.enabled = true;  
  134.                 break;  
  135.             case WarriorActon.eRunAway:  
  136.                 GetComponent<WarriorRunAway>().enabled = true;  
  137.                 break;  
  138.             case WarriorActon.eAlert:  
  139.                 GetComponent<WarriorAlert>().enabled = true;  
  140.                 break;  
  141.             case WarriorActon.eIdle:  
  142.                 GetComponent<WarriorPatrol>().enabled = false;  
  143.                 GetComponent<WarriorAttack>().enabled = false;  
  144.                 GetComponent<WarriorRunAway>().enabled = false;  
  145.                 break;  
  146.         }  
  147.     }  

0 0
原创粉丝点击