using Dependencies.ValakhP.Scripts;
using Explosions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BombController : SSingleton<BombController>
{
private bool hasChainReaction = true;
private float delayChainReaction = 0.6f;
private float detectDistance = 1000000;
private List<Bomb> bombs = new List<Bomb>();
public void Subscribe(Bomb bomb)
{
if (!bombs.Contains(bomb))
{
bombs.Add(bomb);
}
}
public void UnsubscribeAll()
{
bombs = new List<Bomb>();
}
public void ExplodeBomb(Bomb bomb)
{
if (bomb.Exploded && bomb.IsTicking)
{
return;
}
bomb.Exploded = true;
ExplosionUtils.ExplodeWithEffect<Bomb>(bomb.transform.position, bomb.ExplosionForce, bomb.ExplosionRadius);
bomb.gameObject.SetActive(false);
if (hasChainReaction)
{
Bomb nextBomb = null;
var minDistance = float.MaxValue;
foreach (var b in bombs)
{
if (b != bomb)
{
var distance = Vector3.Distance(bomb.transform.position, b.transform.position);
if (distance < detectDistance && distance < minDistance)
{
minDistance = distance;
nextBomb = b;
}
}
}
if (nextBomb != null)
{
StartCoroutine(ExplodeWithDelay(nextBomb));
}
}
}
public IEnumerator ExplodeWithDelay(Bomb bomb)
{
bomb.IsTicking = true;
yield return new WaitForSeconds(delayChainReaction);
ExplodeBomb(bomb);
}
public void OnCollisionBomb(Bomb bomb, Collision collision)
{
if (bomb.Exploded)
{
return;
}
var rb = collision.gameObject.GetComponent<Rigidbody>();
if (rb != null)
{
if (rb.velocity.magnitude > bomb.Sensitivity)
{
ExplodeBomb(bomb);
}
}
}
}