using UnityEngine;

public class ExplosionEffect : MonoBehaviour
{
    public static void Spawn(Vector3 position, float scale = 1f, int particleCount = 20)
    {
        var explosion = new GameObject("Explosion");
        explosion.transform.position = position;
        explosion.transform.localScale = Vector3.one * scale;
        var effect = explosion.AddComponent<ExplosionEffect>();
        effect.burstCount = particleCount;
    }

    public int burstCount = 20;
    private new ParticleSystem particleSystem;
    private float lifetime = 0.5f;
    private float startTime;

    private void Start()
    {
        startTime = Time.time;
        particleSystem = gameObject.AddComponent<ParticleSystem>();

        var main = particleSystem.main;
        main.loop = false;
        main.duration = lifetime;
        main.startLifetime = lifetime;
        main.startSpeed = 3.5f;
        main.startSize = 0.12f;
        main.startColor = Color.white;
        main.gravityModifier = 0f;

        var emission = particleSystem.emission;
        emission.enabled = true;
        emission.rateOverTime = 0;
        emission.SetBurst(0, new ParticleSystem.Burst(0f, (short)burstCount));

        var shape = particleSystem.shape;
        shape.enabled = true;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 0.02f;

        var renderer = particleSystem.GetComponent<ParticleSystemRenderer>();
        renderer.material = new Material(Shader.Find("Sprites/Default"));
        renderer.material.color = Color.white;
        renderer.sortingOrder = 5;
    }

    private void Update()
    {
        if (Time.time - startTime > lifetime)
            Destroy(gameObject);
    }
}
