这个框架是Unity wiki上的框架。网址:http://wiki.unity3d.com/index.php/Finite_State_Machine

这就相当于是“模板”吧,自己写的代码,写啥都是一个风格,还是得多读书,多看报啊...

 有限状态机用来做状态转移,比如代码中的例子,NPC有两个状态跟着主角走(状态A),或者沿着自己的路线走(状态B)。有两个转换,其实就是两条边,A->B,B->A.

 框架里面Transition表示边,StateID表示状态,FSMState是一个状态的抽象类,最主要的是Reason方法,就是判断是不是要进行转换,像例子里B状态里写的就是如果npc前面15m有主角,就进行转换,转换的时候又要进行一些个操作。Act方法就是当前状态要做的一些事情。

 具体也没用过这个框架,也不知道理解的对不对。。项目里,我都是硬写乱搞的,网上搜了搜说,有限状态机有很多缺点,我觉得简单的只有几个状态的话,也挺方便的,以后可以尝试一下。

框架:

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. /**
  7. A Finite State Machine System based on Chapter 3.1 of Game Programming Gems 1 by Eric Dybsand
  8.  
  9. Written by Roberto Cezar Bianchini, July 2010
  10.  
  11. How to use:
  12. 1. Place the labels for the transitions and the states of the Finite State System
  13. in the corresponding enums.
  14.  
  15. 2. Write new class(es) inheriting from FSMState and fill each one with pairs (transition-state).
  16. These pairs represent the state S2 the FSMSystem should be if while being on state S1, a
  17. transition T is fired and state S1 has a transition from it to S2. Remember this is a Deterministic FSM.
  18. You can't have one transition leading to two different states.
  19.  
  20. Method Reason is used to determine which transition should be fired.
  21. You can write the code to fire transitions in another place, and leave this method empty if you
  22. feel it's more appropriate to your project.
  23.  
  24. Method Act has the code to perform the actions the NPC is supposed do if it's on this state.
  25. You can write the code for the actions in another place, and leave this method empty if you
  26. feel it's more appropriate to your project.
  27.  
  28. 3. Create an instance of FSMSystem class and add the states to it.
  29.  
  30. 4. Call Reason and Act (or whichever methods you have for firing transitions and making the NPCs
  31. behave in your game) from your Update or FixedUpdate methods.
  32.  
  33. Asynchronous transitions from Unity Engine, like OnTriggerEnter, SendMessage, can also be used,
  34. just call the Method PerformTransition from your FSMSystem instance with the correct Transition
  35. when the event occurs.
  36.  
  37. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  38. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  39. AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  40. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  42. */
  43.  
  44. /// <summary>
  45. /// Place the labels for the Transitions in this enum.
  46. /// Don't change the first label, NullTransition as FSMSystem class uses it.
  47. /// </summary>
  48. public enum Transition
  49. {
  50. NullTransition = , // Use this transition to represent a non-existing transition in your system
  51. }
  52.  
  53. /// <summary>
  54. /// Place the labels for the States in this enum.
  55. /// Don't change the first label, NullTransition as FSMSystem class uses it.
  56. /// </summary>
  57. public enum StateID
  58. {
  59. NullStateID = , // Use this ID to represent a non-existing State in your system
  60. }
  61.  
  62. /// <summary>
  63. /// This class represents the States in the Finite State System.
  64. /// Each state has a Dictionary with pairs (transition-state) showing
  65. /// which state the FSM should be if a transition is fired while this state
  66. /// is the current state.
  67. /// Method Reason is used to determine which transition should be fired .
  68. /// Method Act has the code to perform the actions the NPC is supposed do if it's on this state.
  69. /// </summary>
  70. public abstract class FSMState
  71. {
  72. protected Dictionary<Transition, StateID> map = new Dictionary<Transition, StateID>();
  73. protected StateID stateID;
  74. public StateID ID { get { return stateID; } }
  75.  
  76. public void AddTransition(Transition trans, StateID id)
  77. {
  78. // Check if anyone of the args is invalid
  79. if (trans == Transition.NullTransition)
  80. {
  81. Debug.LogError("FSMState ERROR: NullTransition is not allowed for a real transition");
  82. return;
  83. }
  84.  
  85. if (id == StateID.NullStateID)
  86. {
  87. Debug.LogError("FSMState ERROR: NullStateID is not allowed for a real ID");
  88. return;
  89. }
  90.  
  91. // Since this is a Deterministic FSM,
  92. // check if the current transition was already inside the map
  93. if (map.ContainsKey(trans))
  94. {
  95. Debug.LogError("FSMState ERROR: State " + stateID.ToString() + " already has transition " + trans.ToString() +
  96. "Impossible to assign to another state");
  97. return;
  98. }
  99.  
  100. map.Add(trans, id);
  101. }
  102.  
  103. /// <summary>
  104. /// This method deletes a pair transition-state from this state's map.
  105. /// If the transition was not inside the state's map, an ERROR message is printed.
  106. /// </summary>
  107. public void DeleteTransition(Transition trans)
  108. {
  109. // Check for NullTransition
  110. if (trans == Transition.NullTransition)
  111. {
  112. Debug.LogError("FSMState ERROR: NullTransition is not allowed");
  113. return;
  114. }
  115.  
  116. // Check if the pair is inside the map before deleting
  117. if (map.ContainsKey(trans))
  118. {
  119. map.Remove(trans);
  120. return;
  121. }
  122. Debug.LogError("FSMState ERROR: Transition " + trans.ToString() + " passed to " + stateID.ToString() +
  123. " was not on the state's transition list");
  124. }
  125.  
  126. /// <summary>
  127. /// This method returns the new state the FSM should be if
  128. /// this state receives a transition and
  129. /// </summary>
  130. public StateID GetOutputState(Transition trans)
  131. {
  132. // Check if the map has this transition
  133. if (map.ContainsKey(trans))
  134. {
  135. return map[trans];
  136. }
  137. return StateID.NullStateID;
  138. }
  139.  
  140. /// <summary>
  141. /// This method is used to set up the State condition before entering it.
  142. /// It is called automatically by the FSMSystem class before assigning it
  143. /// to the current state.
  144. /// </summary>
  145. public virtual void DoBeforeEntering() { }
  146.  
  147. /// <summary>
  148. /// This method is used to make anything necessary, as reseting variables
  149. /// before the FSMSystem changes to another one. It is called automatically
  150. /// by the FSMSystem before changing to a new state.
  151. /// </summary>
  152. public virtual void DoBeforeLeaving() { }
  153.  
  154. /// <summary>
  155. /// This method decides if the state should transition to another on its list
  156. /// NPC is a reference to the object that is controlled by this class
  157. /// </summary>
  158. public abstract void Reason(GameObject player, GameObject npc);
  159.  
  160. /// <summary>
  161. /// This method controls the behavior of the NPC in the game World.
  162. /// Every action, movement or communication the NPC does should be placed here
  163. /// NPC is a reference to the object that is controlled by this class
  164. /// </summary>
  165. public abstract void Act(GameObject player, GameObject npc);
  166.  
  167. } // class FSMState
  168.  
  169. /// <summary>
  170. /// FSMSystem class represents the Finite State Machine class.
  171. /// It has a List with the States the NPC has and methods to add,
  172. /// delete a state, and to change the current state the Machine is on.
  173. /// </summary>
  174. public class FSMSystem
  175. {
  176. private List<FSMState> states;
  177.  
  178. // The only way one can change the state of the FSM is by performing a transition
  179. // Don't change the CurrentState directly
  180. private StateID currentStateID;
  181. public StateID CurrentStateID { get { return currentStateID; } }
  182. private FSMState currentState;
  183. public FSMState CurrentState { get { return currentState; } }
  184.  
  185. public FSMSystem()
  186. {
  187. states = new List<FSMState>();
  188. }
  189.  
  190. /// <summary>
  191. /// This method places new states inside the FSM,
  192. /// or prints an ERROR message if the state was already inside the List.
  193. /// First state added is also the initial state.
  194. /// </summary>
  195. public void AddState(FSMState s)
  196. {
  197. // Check for Null reference before deleting
  198. if (s == null)
  199. {
  200. Debug.LogError("FSM ERROR: Null reference is not allowed");
  201. }
  202.  
  203. // First State inserted is also the Initial state,
  204. // the state the machine is in when the simulation begins
  205. if (states.Count == )
  206. {
  207. states.Add(s);
  208. currentState = s;
  209. currentStateID = s.ID;
  210. return;
  211. }
  212.  
  213. // Add the state to the List if it's not inside it
  214. foreach (FSMState state in states)
  215. {
  216. if (state.ID == s.ID)
  217. {
  218. Debug.LogError("FSM ERROR: Impossible to add state " + s.ID.ToString() +
  219. " because state has already been added");
  220. return;
  221. }
  222. }
  223. states.Add(s);
  224. }
  225.  
  226. /// <summary>
  227. /// This method delete a state from the FSM List if it exists,
  228. /// or prints an ERROR message if the state was not on the List.
  229. /// </summary>
  230. public void DeleteState(StateID id)
  231. {
  232. // Check for NullState before deleting
  233. if (id == StateID.NullStateID)
  234. {
  235. Debug.LogError("FSM ERROR: NullStateID is not allowed for a real state");
  236. return;
  237. }
  238.  
  239. // Search the List and delete the state if it's inside it
  240. foreach (FSMState state in states)
  241. {
  242. if (state.ID == id)
  243. {
  244. states.Remove(state);
  245. return;
  246. }
  247. }
  248. Debug.LogError("FSM ERROR: Impossible to delete state " + id.ToString() +
  249. ". It was not on the list of states");
  250. }
  251.  
  252. /// <summary>
  253. /// This method tries to change the state the FSM is in based on
  254. /// the current state and the transition passed. If current state
  255. /// doesn't have a target state for the transition passed,
  256. /// an ERROR message is printed.
  257. /// </summary>
  258. public void PerformTransition(Transition trans)
  259. {
  260. // Check for NullTransition before changing the current state
  261. if (trans == Transition.NullTransition)
  262. {
  263. Debug.LogError("FSM ERROR: NullTransition is not allowed for a real transition");
  264. return;
  265. }
  266.  
  267. // Check if the currentState has the transition passed as argument
  268. StateID id = currentState.GetOutputState(trans);
  269. if (id == StateID.NullStateID)
  270. {
  271. Debug.LogError("FSM ERROR: State " + currentStateID.ToString() + " does not have a target state " +
  272. " for transition " + trans.ToString());
  273. return;
  274. }
  275.  
  276. // Update the currentStateID and currentState
  277. currentStateID = id;
  278. foreach (FSMState state in states)
  279. {
  280. if (state.ID == currentStateID)
  281. {
  282. // Do the post processing of the state before setting the new one
  283. currentState.DoBeforeLeaving();
  284.  
  285. currentState = state;
  286.  
  287. // Reset the state to its desired condition before it can reason or act
  288. currentState.DoBeforeEntering();
  289. break;
  290. }
  291. }
  292.  
  293. } // PerformTransition()
  294.  
  295. } //class FSMSystem

例子:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using UnityEngine;
  5.  
  6. [RequireComponent(typeof(Rigidbody))]
  7. public class NPCControl : MonoBehaviour
  8. {
  9. public GameObject player;
  10. public Transform[] path;
  11. private FSMSystem fsm;
  12.  
  13. public void SetTransition(Transition t) { fsm.PerformTransition(t); }
  14.  
  15. public void Start()
  16. {
  17. MakeFSM();
  18. }
  19.  
  20. public void FixedUpdate()
  21. {
  22. fsm.CurrentState.Reason(player, gameObject);
  23. fsm.CurrentState.Act(player, gameObject);
  24. }
  25.  
  26. // The NPC has two states: FollowPath and ChasePlayer
  27. // If it's on the first state and SawPlayer transition is fired, it changes to ChasePlayer
  28. // If it's on ChasePlayerState and LostPlayer transition is fired, it returns to FollowPath
  29. private void MakeFSM()
  30. {
  31. FollowPathState follow = new FollowPathState(path);
  32. follow.AddTransition(Transition.SawPlayer, StateID.ChasingPlayer);
  33.  
  34. ChasePlayerState chase = new ChasePlayerState();
  35. chase.AddTransition(Transition.LostPlayer, StateID.FollowingPath);
  36.  
  37. fsm = new FSMSystem();
  38. fsm.AddState(follow);
  39. fsm.AddState(chase);
  40. }
  41. }
  42.  
  43. public class FollowPathState : FSMState
  44. {
  45. private int currentWayPoint;
  46. private Transform[] waypoints;
  47.  
  48. public FollowPathState(Transform[] wp)
  49. {
  50. waypoints = wp;
  51. currentWayPoint = ;
  52. stateID = StateID.FollowingPath;
  53. }
  54.  
  55. public override void Reason(GameObject player, GameObject npc)
  56. {
  57. // If the Player passes less than 15 meters away in front of the NPC
  58. RaycastHit hit;
  59. if (Physics.Raycast(npc.transform.position, npc.transform.forward, out hit, 15F))
  60. {
  61. if (hit.transform.gameObject.tag == "Player")
  62. npc.GetComponent<NPCControl>().SetTransition(Transition.SawPlayer);
  63. }
  64. }
  65.  
  66. public override void Act(GameObject player, GameObject npc)
  67. {
  68. // Follow the path of waypoints
  69. // Find the direction of the current way point
  70. Vector3 vel = npc.rigidbody.velocity;
  71. Vector3 moveDir = waypoints[currentWayPoint].position - npc.transform.position;
  72.  
  73. if (moveDir.magnitude < )
  74. {
  75. currentWayPoint++;
  76. if (currentWayPoint >= waypoints.Length)
  77. {
  78. currentWayPoint = ;
  79. }
  80. }
  81. else
  82. {
  83. vel = moveDir.normalized * ;
  84.  
  85. // Rotate towards the waypoint
  86. npc.transform.rotation = Quaternion.Slerp(npc.transform.rotation,
  87. Quaternion.LookRotation(moveDir),
  88. * Time.deltaTime);
  89. npc.transform.eulerAngles = new Vector3(, npc.transform.eulerAngles.y, );
  90.  
  91. }
  92.  
  93. // Apply the Velocity
  94. npc.rigidbody.velocity = vel;
  95. }
  96.  
  97. } // FollowPathState
  98.  
  99. public class ChasePlayerState : FSMState
  100. {
  101. public ChasePlayerState()
  102. {
  103. stateID = StateID.ChasingPlayer;
  104. }
  105.  
  106. public override void Reason(GameObject player, GameObject npc)
  107. {
  108. // If the player has gone 30 meters away from the NPC, fire LostPlayer transition
  109. if (Vector3.Distance(npc.transform.position, player.transform.position) >= )
  110. npc.GetComponent<NPCControl>().SetTransition(Transition.LostPlayer);
  111. }
  112.  
  113. public override void Act(GameObject player, GameObject npc)
  114. {
  115. // Follow the path of waypoints
  116. // Find the direction of the player
  117. Vector3 vel = npc.rigidbody.velocity;
  118. Vector3 moveDir = player.transform.position - npc.transform.position;
  119.  
  120. // Rotate towards the waypoint
  121. npc.transform.rotation = Quaternion.Slerp(npc.transform.rotation,
  122. Quaternion.LookRotation(moveDir),
  123. * Time.deltaTime);
  124. npc.transform.eulerAngles = new Vector3(, npc.transform.eulerAngles.y, );
  125.  
  126. vel = moveDir.normalized * ;
  127.  
  128. // Apply the new Velocity
  129. npc.rigidbody.velocity = vel;
  130. }
  131.  
  132. } // ChasePlayerState

基于Unity有限状态机框架的更多相关文章

  1. MVC4 基于 Unity Ioc 框架的 ControllerFactory

    首先引入Untiy框架. 可以在NuGet程序包 管理器中直接安装. 新建 继承DefaultControllerFactory  的UnityControllerFactory: 重写虚方法GetC ...

  2. 关于基于python2.7的unity自动化测试框架GAutomator测试环境的搭建(源码网盘下载地址:https://pan.baidu.com/s/1c2TXwtU)

    关于基于python 2.7的unity自动化测试框架GAutomator测试环境的搭建 百度云盘链接(思维图学习资料):https://pan.baidu.com/s/1dFWExMD 准备工作(具 ...

  3. Unity 游戏框架搭建 (十) QFramework v0.0.2小结

    从框架搭建系列的第一篇文章开始到现在有四个多月时间了,这段时间对自己来说有很多的收获,好多小伙伴和前辈不管是在评论区还是私下里给出的建议非常有参考性,在此先谢过各位. 说到是一篇小节,先列出框架的概要 ...

  4. 基于Qt有限状态机的一种实现方式和完善的人工智能方法

    基于Qt有限状态机的一种实现方式和完善的人工智能方法 人工智能在今年是一个非常火的方向,当然了.不不过今年,它一直火了非常多年,有关人工智能的一些算法层出不穷.人工智能在非常多领域都有应用,就拿我熟悉 ...

  5. Unity 游戏框架搭建 2018 (一) 架构、框架与 QFramework 简介

    约定 还记得上版本的第二十四篇的约定嘛?现在出来履行啦~ 为什么要重制? 之前写的专栏都是按照心情写的,在最初的时候笔者什么都不懂,而且文章的发布是按照很随性的一个顺序.结果就是说,大家都看完了,都还 ...

  6. Unity 游戏框架搭建 (十六) v0.0.1 架构调整

    背景: 前段时间用Xamarin.OSX开发一些工具,遇到了两个问题. QFramework的大部分的类耦合了Unity的API,这样导致不能在其他CLR平台使用QFramework. QFramew ...

  7. Unity StrangeIoC框架

    Unity StrangeIoC框架  http://blog.csdn.net/y1196645376/article/details/52746251    

  8. 基于Java Netty框架构建高性能的部标808协议的GPS服务器

    使用Java语言开发一个高质量和高性能的jt808 协议的GPS通信服务器,并不是一件简单容易的事情,开发出来一段程序和能够承受数十万台车载接入是两码事,除去开发部标808协议的固有复杂性和几个月长周 ...

  9. 基于Typecho CMS框架开发大中型应用

    基于Typecho CMS框架开发大中型应用 大中型应用暂且定义为:大于等于3个数据表的应用!汗吧! Typecho原本是一款博客系统,其框架体系有别于市面上一般意义MVC框架,主体代码以自创的Wid ...

随机推荐

  1. js_面向对象

    面向对象的语言有一个标志,即拥有类的概念,抽象实例对象的公共属性与方法,基于类可以创建任意多个实例对象,一般具有封装.继承.多态的特性!但JS中对象与纯面向对象语言中的对象是不同的,ECMA标准定义J ...

  2. IIS性能提升

    1. 调整IIS 7应用程序池队列长度 由原来的默认1000改为65535. IIS Manager > ApplicationPools > Advanced Settings Queu ...

  3. jquery样式篇

    1.jquery: 1.1简介 jquery是一个轻量级的javascript库.版本号分1.x版本和2.x版本,2.x版本不再支持IE6 7 8,而更好的支 持移动端开发. 每一个版本分为开发版和压 ...

  4. OpenLayers.2.10.Beginners.Guide---第一章

    从网上下载openlayers2,解压取得img theme 文件夹和openlayes.js文件.放在同一文件夹下用phpstorm打开. 创建index.html-------------每一行都 ...

  5. Sqlserver 2008清除数据库日志

    USE [master] GO ALTER DATABASE DBNAME SET RECOVERY SIMPLE WITH NO_WAIT GO ALTER DATABASE DBNAME SET ...

  6. 解决java.lang.NoClassDefFoundError: org/objectweb/asm/util/TraceClassVisitor

    方案一: <dependency> <groupId>asm</groupId> <artifactId>asm-all</artifactId& ...

  7. JPA快速入门(自用)

    该案例为JPA的实体映射案例,将该项目解压导入到myeclipse中即可使用,然后直接使用hibernate即可! 文件地址:files.cnblogs.com/mrwangblog/JPA-Hibe ...

  8. MongoDB安装并随windows开机自启

    MongoDB的官方下载站是http://www.mongodb.org/downloads,可以去上面下载最新的程序下来.在下载页面可以看到,对操作系统支持很全面,OS X.Linux.Window ...

  9. ethhdr、ether_header、iphdr、tcphdr、udphdr 结构介绍

    转自:http://blog.csdn.net/petershina/article/details/8573853 ************************eth的结构*********** ...

  10. Android学习资源整理

    官方文档:https://developer.android.com/guide/index.html (万万没想到居然有中文) 网友整理的学习笔记,挺不错的 http://www.runoob.co ...