- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- public class NavMeshAgentController : MonoBehaviour
- {
- private NavMeshAgent agent;
- private FiniteStateMachine fsm;
- public List<Waypoint> waypoints;
- public Vector3 currentTarget;
- private int index = 0;
- private void Awake()
- {
- fsm = GetComponent<FiniteStateMachine>();
- agent = GetComponent<NavMeshAgent>();
- }
- public bool SetDestination(Vector3 position)
- {
- if (agent.IsAtDestination()) {
- Stop();
- currentTarget = position;
- return agent.SetDestination(position);
- }
- return false;
- }
- public void Stop()
- {
- agent.isStopped = true;
- agent.ResetPath();
- }
- public bool IsStopped()
- {
- return agent.isStopped;
- }
-
- public bool MoveToTarget()
- {
- return SetDestination(fsm.target.position);
- }
- public void MoveToWaypoint()
- {
-
- if (IsAtDestination())
- {
- SetDestination(waypoints[index].transform.position);
- index++;
- if (index >= waypoints.Count) index = 0;
- }
- }
- public void MoveToNearestWaypoint()
- {
- Waypoint waypoint = GetNearestWaypoint();
- if (waypoint != null && IsAtDestination())
- {
- SetDestination(waypoint.transform.position);
- }
- }
- public Waypoint GetNearestWaypoint()
- {
- if (waypoints.Count > 0)
- {
- Waypoint nearestWaypoint = waypoints[0];
- float distance = float.MaxValue;
- foreach (Waypoint wp in waypoints)
- {
- float calculatedDistance = Vector3.Distance(wp.transform.position, transform.position);
- if (calculatedDistance < distance)
- {
- nearestWaypoint = wp;
- distance = calculatedDistance;
- }
- }
-
- return nearestWaypoint;
-
- }
- return null;
-
- }
- public bool IsAtDestination()
- {
- return agent.IsAtDestination();
- }
- }