AgentLinkMover.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // AgentLinkMover.cs
  2. using UnityEngine;
  3. using System.Collections;
  4. using UnityEngine.AI;
  5. public enum OffMeshLinkMoveMethod
  6. {
  7. Teleport,
  8. NormalSpeed,
  9. Parabola,
  10. Curve
  11. }
  12. [RequireComponent(typeof(NavMeshAgent))]
  13. public class AgentLinkMover : MonoBehaviour
  14. {
  15. public OffMeshLinkMoveMethod method = OffMeshLinkMoveMethod.Parabola;
  16. public AnimationCurve curve = new AnimationCurve();
  17. IEnumerator Start()
  18. {
  19. NavMeshAgent agent = GetComponent<NavMeshAgent>();
  20. agent.autoTraverseOffMeshLink = false;
  21. while (true)
  22. {
  23. if (agent.isOnOffMeshLink)
  24. {
  25. if (method == OffMeshLinkMoveMethod.NormalSpeed)
  26. yield return StartCoroutine(NormalSpeed(agent));
  27. else if (method == OffMeshLinkMoveMethod.Parabola)
  28. yield return StartCoroutine(Parabola(agent, 2.0f, 0.5f));
  29. else if (method == OffMeshLinkMoveMethod.Curve)
  30. yield return StartCoroutine(Curve(agent, 0.5f));
  31. agent.CompleteOffMeshLink();
  32. }
  33. yield return null;
  34. }
  35. }
  36. IEnumerator NormalSpeed(NavMeshAgent agent)
  37. {
  38. OffMeshLinkData data = agent.currentOffMeshLinkData;
  39. Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
  40. while (agent.transform.position != endPos)
  41. {
  42. agent.transform.position = Vector3.MoveTowards(agent.transform.position, endPos, agent.speed * Time.deltaTime);
  43. yield return null;
  44. }
  45. }
  46. IEnumerator Parabola(NavMeshAgent agent, float height, float duration)
  47. {
  48. OffMeshLinkData data = agent.currentOffMeshLinkData;
  49. Vector3 startPos = agent.transform.position;
  50. Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
  51. float normalizedTime = 0.0f;
  52. while (normalizedTime < 1.0f)
  53. {
  54. float yOffset = height * 4.0f * (normalizedTime - normalizedTime * normalizedTime);
  55. agent.transform.position = Vector3.Lerp(startPos, endPos, normalizedTime) + yOffset * Vector3.up;
  56. normalizedTime += Time.deltaTime / duration;
  57. yield return null;
  58. }
  59. }
  60. IEnumerator Curve(NavMeshAgent agent, float duration)
  61. {
  62. OffMeshLinkData data = agent.currentOffMeshLinkData;
  63. Vector3 startPos = agent.transform.position;
  64. Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
  65. float normalizedTime = 0.0f;
  66. while (normalizedTime < 1.0f)
  67. {
  68. float yOffset = curve.Evaluate(normalizedTime);
  69. agent.transform.position = Vector3.Lerp(startPos, endPos, normalizedTime) + yOffset * Vector3.up;
  70. normalizedTime += Time.deltaTime / duration;
  71. yield return null;
  72. }
  73. }
  74. }