jimmy tremblay-Bernier c1bf5a4ca1 initial commit
2022-03-12 22:04:30 -04:00

86 lines
3.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AlliesManager : MonoBehaviour
{
public GameObject m_soldierPrefab;
public GameObject[] m_spawnPoint;
public GameObject[] m_soldierTargetLocation;
public int m_soldierToSpawn = 4;
public float m_timeSoldierStaysInPosition = 30f;// seconds
public float m_delayBetweenSpawnPerSpawnPoint = 2f;
private GameObject[] m_soldierList;
private Dictionary<GameObject, DateTime> m_spawnLastTime = new Dictionary<GameObject, DateTime>();
private int m_SoldierLeftToSpawn = 0;
private int m_lastTargetIndex = 0;
private List<GameObject> m_existingSoldiers = new List<GameObject>();
private DateTime m_waveStartTime = DateTime.MinValue;
// Start is called before the first frame update
void Start()
{
//StartSupport();
}
public void StartSupport()
{
m_waveStartTime = DateTime.Now;
m_SoldierLeftToSpawn += m_soldierToSpawn;
}
void TrySpawnSupport()
{
int indexForSpawn = m_lastTargetIndex % m_spawnPoint.Length;
int indexForTarget = m_lastTargetIndex % m_soldierTargetLocation.Length;
if (!m_spawnLastTime.ContainsKey(m_spawnPoint[indexForSpawn]))// Init if it's the first time a spawn point is seen
{
m_spawnLastTime[m_spawnPoint[indexForSpawn]] = DateTime.MinValue;
}
double timeLeftForSpecificSpawn = (DateTime.Now - m_spawnLastTime[m_spawnPoint[indexForSpawn]]).TotalSeconds;
if (timeLeftForSpecificSpawn > m_delayBetweenSpawnPerSpawnPoint)
{
m_spawnLastTime[m_spawnPoint[indexForSpawn]] = DateTime.Now;
GameObject ally = Instantiate(m_soldierPrefab);
ally.GetComponent<AlliesMovement>().targetPosition = m_soldierTargetLocation[indexForTarget];
ally.GetComponent<AlliesMovement>().ExitPosition = m_spawnPoint[indexForSpawn];
ally.GetComponent<NavMeshAgent>().Warp(m_spawnPoint[indexForSpawn].transform.position);
m_existingSoldiers.Add(ally);
m_SoldierLeftToSpawn--;
m_lastTargetIndex++;
}
}
void FixedUpdate()
{
if ((DateTime.Now - m_waveStartTime).TotalSeconds < m_timeSoldierStaysInPosition)
{
if (m_SoldierLeftToSpawn > 0)
{
TrySpawnSupport();
}
}
else
{// Replace the target location to the exit, then delete when they are close enough to the exit
foreach(var ally in m_existingSoldiers)
{
AlliesMovement mov = ally.GetComponent<AlliesMovement>();
if(mov.targetPosition != mov.ExitPosition)
{
mov.targetPosition = mov.ExitPosition;
} else
{
if(Vector3.Distance(ally.transform.position, mov.ExitPosition.transform.position) < 1f)
{
m_existingSoldiers.Remove(ally);
Destroy(ally);
}
}
}
}
}
}