Projet-IA-Madelaine/Scripts/Spawners/MissileSpawnerScript.cs

121 lines
3.0 KiB
C#
Raw Normal View History

2024-06-12 21:03:42 +02:00
using Assets.Scripts;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static LevelSpawner;
public class MissileSpawnerScript : MonoBehaviour
{
#region PROPERTIES
#endregion
#region VARIABLES
public float alertDuration = 5f;
private int baseCountdown = 2;
private int countdown = 0;
private bool renderSprite;
private MissileAlertScript missileAlertScript;
private PlayerScript playerScript;
private GameHandler _gameHandler;
private DataBearer _dataBearer;
private PlayersHandler _playersHandler;
private LevelSpawner _leverSpawner;
[SerializeField] private GameObject missileAlertRef;
[SerializeField] private GameObject missilePrefab;
#endregion
#region EVENTS
public event EventHandler<MissileEventArgs> OnMissileAlert;
public event EventHandler<MissileEventArgs> OnMissileLaunched;
public class MissileEventArgs : EventArgs
{
//todo : eventContent
}
private void MissileLaunchCountdown_OnPrefab(object sender, PrefabSpawnedEventArgs args)
{
if (countdown == baseCountdown)
{
StartCoroutine(MissileLaunchSequence());
countdown = 0;
}
else
{
countdown++;
}
}
#endregion
#region METHODS
private IEnumerator MissileLaunchSequence()
{
if(renderSprite)
missileAlertScript.enabled = true;
yield return new WaitForSeconds(alertDuration);
missileAlertScript.enabled = false;
SpawnMissile();
}
private void SpawnMissile()
{
var position = new Vector3(20, transform.position.y, -2);
var instance = Instantiate(missilePrefab, position, missilePrefab.transform.rotation);
instance.GetComponent<MissileScript>().SetTarget(playerScript.Id);
instance.GetComponent<MissileScript>().SetRenderSprite(renderSprite);
if (!renderSprite)
{
DestroyImmediate(instance.GetComponent<SpriteRenderer>(), true);
instance.GetComponent<MissileScript>().StopParticles();
}
}
#endregion
#region LIFECYCLE
protected void Awake()
{
_dataBearer = DataBearer.Instance;
_gameHandler = GameHandler.Instance;
_playersHandler = PlayersHandler.Instance;
_leverSpawner = LevelSpawner.Instance;
if (!_dataBearer.Rules.Missiles)
{
Destroy(gameObject);
}
_leverSpawner.OnPrefabSpawned += MissileLaunchCountdown_OnPrefab;
missileAlertScript = missileAlertRef.GetComponent<MissileAlertScript>();
playerScript = GetComponentInParent<PlayerScript>();
}
private void Start()
{
renderSprite = !(_gameHandler.HaveHumanPlayer && !playerScript.IsHuman); // false if game has human and script is not human
}
private void OnDestroy()
{
Clean();
}
private void Clean()
{
StopAllCoroutines();
LevelSpawner.Instance.OnPrefabSpawned -= MissileLaunchCountdown_OnPrefab;
}
#endregion
}