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

83 lines
2.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
using UnityUtils;
public class WaypointPath : MonoBehaviour
{
[SerializeField] private float WaypointRadiusTolerence = 0.01f;
[SerializeField] public List<Transform> Waypoints;
[SerializeField] public List<WaypointEntityData> activeEntities = new();
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
GameManager.Instance.health--;
}
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;
Debug.Log(data.FeetOffset);
data.Entity.position = data.Entity.position.With(y: data.FeetOffset);
}
}
public void AddObjectToPath(WaypointEntityData data)
{
activeEntities.Add(data);
}
}
public class WaypointEntityData
{
public Transform Entity;
public Transform NextTargetPosition;
public float MoveSpeed;
public float FeetOffset;
public WaypointEntityData(Transform entity, float moveSpeed, float feet)
{
Entity = entity;
MoveSpeed = moveSpeed;
// feet :P
FeetOffset = feet;
}
}