Newer
Older
Dreamsturbia-Project-IADE-Unity3D / Assets / Scripts / AI / Navmesh / NavMeshAgentController.cs
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.AI;
  5. public class NavMeshAgentController : MonoBehaviour
  6. {
  7. private NavMeshAgent agent;
  8. private FiniteStateMachine fsm;
  9. public List<Waypoint> waypoints;
  10. public Vector3 currentTarget;
  11. private int index = 0;
  12. private void Awake()
  13. {
  14. fsm = GetComponent<FiniteStateMachine>();
  15. agent = GetComponent<NavMeshAgent>();
  16. }
  17. public bool SetDestination(Vector3 position)
  18. {
  19. if (agent.IsAtDestination()) {
  20. Stop();
  21. currentTarget = position;
  22. return agent.SetDestination(position);
  23. }
  24. return false;
  25. }
  26. public void Stop()
  27. {
  28. agent.isStopped = true;
  29. agent.ResetPath();
  30. }
  31. public bool IsStopped()
  32. {
  33. return agent.isStopped;
  34. }
  35. public bool MoveToTarget()
  36. {
  37. return SetDestination(fsm.target.position);
  38. }
  39. public void MoveToWaypoint()
  40. {
  41. if (IsAtDestination())
  42. {
  43. SetDestination(waypoints[index].transform.position);
  44. index++;
  45. if (index >= waypoints.Count) index = 0;
  46. }
  47. }
  48. public void MoveToNearestWaypoint()
  49. {
  50. Waypoint waypoint = GetNearestWaypoint();
  51. if (waypoint != null && IsAtDestination())
  52. {
  53. SetDestination(waypoint.transform.position);
  54. }
  55. }
  56. public Waypoint GetNearestWaypoint()
  57. {
  58. if (waypoints.Count > 0)
  59. {
  60. Waypoint nearestWaypoint = waypoints[0];
  61. float distance = float.MaxValue;
  62. foreach (Waypoint wp in waypoints)
  63. {
  64. float calculatedDistance = Vector3.Distance(wp.transform.position, transform.position);
  65. if (calculatedDistance < distance)
  66. {
  67. nearestWaypoint = wp;
  68. distance = calculatedDistance;
  69. }
  70. }
  71. return nearestWaypoint;
  72. }
  73. return null;
  74. }
  75. public bool IsAtDestination()
  76. {
  77. return agent.IsAtDestination();
  78. }
  79. }