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

82 lines
2.4 KiB
C#
Raw Normal View History

2024-04-21 04:53:57 +02:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
2024-04-21 09:40:42 +02:00
using UnityUtils;
2024-04-21 04:53:57 +02:00
2024-04-21 05:59:29 +02:00
public class WaypointPath : MonoBehaviour
2024-04-21 04:53:57 +02:00
{
[SerializeField] private float WaypointRadiusTolerence = 0.1f;
[SerializeField] public List<Transform> Waypoints;
2024-04-21 04:53:57 +02:00
[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
2024-04-21 07:33:18 +02:00
GameManager.Instance.health--;
2024-04-21 04:53:57 +02:00
}
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;
2024-04-21 13:55:46 +02:00
data.Entity.right = -normTargetDir;
2024-04-21 04:53:57 +02:00
}
}
public void AddObjectToPath(WaypointEntityData data)
{
activeEntities.Add(data);
}
}
public class WaypointEntityData
{
public Transform Entity;
public Transform NextTargetPosition;
public float MoveSpeed;
2024-04-21 09:40:42 +02:00
public float FeetOffset;
2024-04-21 05:59:29 +02:00
2024-04-21 09:40:42 +02:00
public WaypointEntityData(Transform entity, float moveSpeed, float feet)
2024-04-21 05:59:29 +02:00
{
Entity = entity;
MoveSpeed = moveSpeed;
2024-04-21 09:40:42 +02:00
// feet :P
FeetOffset = feet;
2024-04-21 05:59:29 +02:00
}
2024-04-21 04:53:57 +02:00
}