using System; using Grid; using UnityEngine; using Random = UnityEngine.Random; public class Crate : MonoBehaviour, IDestructable { [SerializeField] private Transform crateDestroyedPrefab; private void Start() => GridPosition = LevelGrid.Instance.GetGridPosition(transform.position); public GridPosition GridPosition { get; set; } public void Damage(float damageAmount) { Transform crateDestroyedTransform = Instantiate(crateDestroyedPrefab, transform.position, transform.rotation); ApplyExplosionToChildren(crateDestroyedTransform, Random.Range(damageAmount - 50f, damageAmount + 50f), transform.position, Random.Range(damageAmount / 10f, damageAmount / 5f)); Destroy(gameObject); OnAnyDestroyed?.Invoke(this, EventArgs.Empty); } public static event EventHandler OnAnyDestroyed; private static void ApplyExplosionToChildren(Transform root, float explosionForce, Vector3 explosionPosition, float explosionRadius) { foreach (Transform child in root) { if (!child.TryGetComponent(out Rigidbody childRigidbody)) continue; childRigidbody.AddExplosionForce(explosionForce, explosionPosition, explosionRadius); ApplyExplosionToChildren(child, explosionForce, explosionPosition, explosionRadius); } } }