ActionFollowTarget.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using UnityEngine;
  2. using System.Collections;
  3. using BehaviorDesigner.Runtime;
  4. using BehaviorDesigner.Runtime.Tasks;
  5. using UnityEngine.AI;
  6. /// <summary>
  7. /// 跟随目标
  8. /// </summary>
  9. public class ActionFollowTarget : Action
  10. {
  11. /// <summary>
  12. /// 跟随的最近距离
  13. /// </summary>
  14. public float followDistance = 2.0f;
  15. /// <summary>
  16. /// 跟随的目标
  17. /// </summary>
  18. public SharedTransform target;
  19. /// <summary>
  20. /// 角色
  21. /// </summary>
  22. private Role role = null;
  23. /// <summary>
  24. /// 跟随距离
  25. /// </summary>
  26. private float sqrFollowDistance = 0;
  27. public override void OnAwake()
  28. {
  29. role = GetComponent<Role>();
  30. }
  31. public override void OnStart()
  32. {
  33. sqrFollowDistance = followDistance * followDistance;
  34. //启用导航组件
  35. role.mNavMeshAgent.enabled = true;
  36. if (target != null && target.Value != null)
  37. {
  38. role.mNavMeshAgent.destination = target.Value.position;
  39. }
  40. }
  41. public override void OnEnd()
  42. {
  43. role.mNavMeshAgent.enabled = false;
  44. }
  45. //如果抢夺者在视野内,就追, 否则就认为防御成功
  46. public override TaskStatus OnUpdate()
  47. {
  48. //做一个安全的校验
  49. if (target == null && target.Value == null)
  50. {
  51. return TaskStatus.Failure;
  52. }
  53. float sqrDistance = (target.Value.position - transform.position).sqrMagnitude;
  54. if (sqrDistance > sqrFollowDistance)
  55. {
  56. if (role.mNavMeshAgent.destination != target.Value.position)
  57. {
  58. role.mNavMeshAgent.destination = target.Value.position;
  59. }
  60. return TaskStatus.Running;
  61. }
  62. else
  63. {
  64. return TaskStatus.Success;
  65. }
  66. }
  67. }