3DTD/Assets/Scripts/Manager/WaypointSystemManager.cs

89 lines
2.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
public class WaypointSystemManager : MonoBehaviour
{
public static WaypointSystemManager Instance;
[SerializeField] private float WaypointRadiusTolerence = 0.01f;
[SerializeField] private List<Transform> Waypoints;
[SerializeField] public List<WaypointEntityData> activeEntities = new();
public GameObject DebugPrefab;
private void OnEnable()
{
if (Instance != null)
Destroy(Instance);
Instance = this;
}
private void Start()
{
var data = new WaypointEntityData();
data.Entity = Instantiate(DebugPrefab).transform;
data.MoveSpeed = 1;
AddObjectToPath(data);
}
private void Update()
{
for (int i = 0; i < activeEntities.Count; i++)
{
var data = activeEntities[i];
// Check if entity still exists
if (data.Entity == null)
{
activeEntities.RemoveAt(i);
continue;
}
// Set target if no target
if (data.NextTargetPosition == null)
data.NextTargetPosition = Waypoints[0];
// Changes target if within tolerence
if (Vector3.Distance(data.Entity.position, data.NextTargetPosition.position) < WaypointRadiusTolerence)
{
int index = Waypoints.IndexOf(data.NextTargetPosition);
if (index + 1 >= Waypoints.Count)
{
Destroy(data.Entity.gameObject); // Destroy object when finish waypoints
}
else
{
data.NextTargetPosition = Waypoints[index + 1];
}
}
// Move object by speed
Vector3 targetDirection = data.NextTargetPosition.position - data.Entity.position;
Vector3 normTargetDir = targetDirection.normalized;
float dist = Vector3.Distance(data.Entity.position, data.NextTargetPosition.position);
float minDist = Math.Min(dist, data.MoveSpeed * Time.deltaTime);
data.Entity.position += normTargetDir * minDist;
}
}
public void AddObjectToPath(WaypointEntityData data)
{
activeEntities.Add(data);
}
}
public class WaypointEntityData
{
public Transform Entity;
public Transform NextTargetPosition;
public float MoveSpeed;
}