Implement enemy spawning and following waypoints
This commit is contained in:
76
Assets/Scripts/Components/NavMeshComponent.cs
Normal file
76
Assets/Scripts/Components/NavMeshComponent.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user