84 lines
2.5 KiB
C#
84 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.1f;
|
|
[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 -= data.Damage;
|
|
}
|
|
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;
|
|
data.Entity.right = -normTargetDir;
|
|
}
|
|
}
|
|
|
|
public void AddObjectToPath(WaypointEntityData data)
|
|
{
|
|
activeEntities.Add(data);
|
|
}
|
|
}
|
|
|
|
public class WaypointEntityData
|
|
{
|
|
public Transform Entity;
|
|
public Transform NextTargetPosition;
|
|
public float MoveSpeed;
|
|
public float FeetOffset;
|
|
public int Damage;
|
|
|
|
public WaypointEntityData(Transform entity, float moveSpeed, float feet, int damage)
|
|
{
|
|
Entity = entity;
|
|
MoveSpeed = moveSpeed;
|
|
|
|
// feet :P
|
|
FeetOffset = feet;
|
|
Damage = damage;
|
|
}
|
|
}
|