AgentLinkMover.cs 2.8 KB

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