Files
dungeons/Assets/Scripts/Components/NavMeshComponent.cs

77 lines
1.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
using UnityEngine.AI;
using UnityEngine.Events;
[RequireComponent(typeof(NavMeshAgent))]
public class NavMeshComponent : MonoBehaviour
{
[SerializeField]
[ReadOnly]
public int currentWaypointIndex = 0;
[SerializeField]
[ReadOnly]
public WaypointsGroup waypointGroup;
[SerializeField]
[ReadOnly]
private NavMeshAgent agent;
[SerializeField]
private UnityEvent<float> onVelocityChanged;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
public void MoveTo(WaypointsGroup waypointGroup)
{
this.waypointGroup = waypointGroup;
MoveToNext();
}
private void MoveToNext()
{
currentWaypointIndex++;
agent.destination = waypointGroup.waypoints[currentWaypointIndex]
.GetPosition();
}
private void Update()
{
var velocity = agent.velocity.magnitude / agent.speed;
onVelocityChanged.Invoke(velocity);
if (waypointGroup == null)
return;
if (ReachedDestinationOrGaveUp())
{
if (currentWaypointIndex != waypointGroup.waypoints.Count - 1)
{
MoveToNext();
}
}
}
private bool ReachedDestinationOrGaveUp()
{
if (agent.pathPending)
return false;
if (agent.remainingDistance > agent.stoppingDistance)
return false;
if (!(!agent.hasPath || agent.velocity.sqrMagnitude == 0f))
return false;
return true;
}
}