using UnityEngine;
using UnityEngine.VFX;

[ExecuteAlways]
public class SwarmAnimator : MonoBehaviour
{
    [SerializeField] private VisualEffect vfx;

    [SerializeField] private Rigidbody rb;
    //[SerializeField]
    //private string parameterName = "DeltaVector";

    [SerializeField] private Vector3 avoidancePosDefault;

    [SerializeField] private float explodeDuration = 1.0f;

    private Vector3 currentPosition;
    private float dur;
    private bool isExploding;
    private Vector3 previousPosition;

    // Start is called before the first frame update
    private void Start()
    {
    }

    // Update is called once per frame
    private void Update()
    {
        previousPosition = currentPosition;
        currentPosition = transform.position;
        var velocity = currentPosition - previousPosition;
        vfx.SetVector3("DeltaVector", velocity);

        if (Input.GetKeyDown(KeyCode.Space)) Explode();
        if (isExploding)
        {
            if (dur > explodeDuration) StopExplode();
            dur += Time.deltaTime;
        }
    }

    private void FixedUpdate()
    {
    }

    private void Explode()
    {
        vfx.SetVector3("Avoid", transform.position);
        isExploding = true;
        dur = 0;

        //Wait a sec then stop.
    }

    private void StopExplode()
    {
        vfx.SetVector3("Avoid", avoidancePosDefault);
        isExploding = false;
        vfx.Stop();
    }
}