ActionKitFSMExample.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using UnityEngine;
  2. namespace QFramework.Example.ActionKit
  3. {
  4. public class ActionKitFSMExample : MonoBehaviour
  5. {
  6. /// <summary>
  7. /// 走状态
  8. /// </summary>
  9. class WalkState : ActionKitFSMState<ActionKitFSMExample>
  10. {
  11. public WalkState(ActionKitFSMExample target) : base(target)
  12. {
  13. }
  14. protected override void OnEnter()
  15. {
  16. Debug.Log("进入 走 状态");
  17. }
  18. protected override void OnExit()
  19. {
  20. Debug.Log("退出 走 状态");
  21. }
  22. }
  23. /// <summary>
  24. /// 跑状态
  25. /// </summary>
  26. class RunState : ActionKitFSMState<ActionKitFSMExample>
  27. {
  28. public RunState(ActionKitFSMExample target) : base(target)
  29. {
  30. }
  31. protected override void OnEnter()
  32. {
  33. Debug.Log("进入 跑 状态");
  34. }
  35. protected override void OnExit()
  36. {
  37. Debug.Log("退出 跑 状态");
  38. }
  39. }
  40. /// <summary>
  41. /// 空格键按下 走=>跑
  42. /// </summary>
  43. class SpaceKeyDown : ActionKitFSMTransition<WalkState,RunState>
  44. {
  45. }
  46. /// <summary>
  47. /// 空格键按起 跑=>走
  48. /// </summary>
  49. class SpaceKeyUp : ActionKitFSMTransition<RunState,WalkState>
  50. {
  51. }
  52. /// <summary>
  53. /// 状态机
  54. /// </summary>
  55. ActionKitFSM mFsm = new ActionKitFSM();
  56. void Awake()
  57. {
  58. var walkState = new WalkState(this);
  59. var runState = new RunState(this);
  60. mFsm.AddState(walkState);
  61. mFsm.AddState(runState);
  62. mFsm.AddTransition(new SpaceKeyDown());
  63. mFsm.AddTransition(new SpaceKeyUp());
  64. mFsm.StartState<WalkState>();
  65. }
  66. private void Update()
  67. {
  68. if (Input.GetKeyDown(KeyCode.Space))
  69. {
  70. mFsm.HandleEvent<SpaceKeyDown>();
  71. }
  72. if (Input.GetKeyUp(KeyCode.Space))
  73. {
  74. mFsm.HandleEvent<SpaceKeyUp>();
  75. }
  76. }
  77. }
  78. }