CharacterMoveToTargetTaskAction.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using NodeCanvas.Framework;
  5. using ParadoxNotion.Design;
  6. using KairoEngine.Core;
  7. namespace KairoEngine.CharacterSystem
  8. {
  9. public enum MoveSpeed
  10. {
  11. walk,
  12. run
  13. }
  14. [Category("KairoEngine")]
  15. public class CharacterMoveToTargetTaskAction : ActionTask
  16. {
  17. [BlackboardOnly, RequiredField] public BBParameter<CharacterController> character;
  18. [BlackboardOnly, RequiredField] public BBParameter<Transform> target;
  19. [RequiredField] public BBParameter<float> attackDistance = 1f;
  20. public MoveSpeed moveSpeed = MoveSpeed.walk;
  21. public BBParameter<float> lostTargetTimer = 1f;
  22. private float counter = 0f;
  23. private Transform _target;
  24. private Vector3 pos;
  25. private bool success = true;
  26. private bool done = false;
  27. protected override string info {
  28. get { return "Move character to target"; }
  29. }
  30. protected override void OnExecute()
  31. {
  32. _target = target.value;
  33. IssueCommand();
  34. counter = 0f;
  35. }
  36. protected override void OnUpdate()
  37. {
  38. if(target.value == null && !done)
  39. {
  40. counter += Time.deltaTime;
  41. if(counter > lostTargetTimer.value)
  42. {
  43. EndAction(false);
  44. }
  45. }
  46. else counter = 0f;
  47. float distance = Vector3.Distance(character.value.transform.position, _target.position);
  48. if(distance < attackDistance.value) EndAction(true);
  49. float distanceFromTarget = Vector3.Distance(_target.position, pos);
  50. if(distanceFromTarget > 1f && !done)
  51. {
  52. GenericEvents.StopListening(character.value.unique_name + "-ArrivedInPositionAction", End);
  53. IssueCommand();
  54. done = false;
  55. }
  56. }
  57. protected override void OnStop()
  58. {
  59. GenericEvents.StopListening(character.value.unique_name + "-ArrivedInPositionAction", End);
  60. ICommand stopCommand = new CharacterStopMoveCommand(character.value);
  61. CommandInvoker.AddCommand(stopCommand);
  62. }
  63. private void End()
  64. {
  65. EndAction(success);
  66. }
  67. private void IssueCommand()
  68. {
  69. float translationSpeed = 1.25f;
  70. float animationSpeed = 1f;
  71. if(moveSpeed == MoveSpeed.run)
  72. {
  73. translationSpeed = 3.5f;
  74. animationSpeed = 2f;
  75. }
  76. pos = _target.position;
  77. GenericEvents.StartListening(character.value.unique_name + "-ArrivedInPositionAction", End);
  78. ICommand movecommand = new CharacterMoveToPositionCommand(character.value, pos, translationSpeed, animationSpeed, attackDistance.value);
  79. CommandInvoker.AddCommand(movecommand);
  80. }
  81. }
  82. }