using System;
using System.Collections;
using UnityEngine;

public class HitEffect : MonoBehaviour
{

    [SerializeField] private float lifeTime = 0.2f;
    [SerializeField] private bool flipWithDirection = true;

    private SpriteRenderer _sr;
    private Coroutine _lifeRoutine;
    private Animator _animator;
    private void Awake()
    {
        _sr = GetComponent<SpriteRenderer>();
        _animator = GetComponent<Animator>();
    }
    
    /// <summary>
    /// Called by HitEffectManager when this effect is spawned.
    /// </summary>
    public void Play(Vector2 direction)
    {
        if (flipWithDirection && _sr != null)
        {
            _sr.flipX = direction.x < 0f;
        }

        if (_lifeRoutine != null)
        {
            StopCoroutine(_lifeRoutine);
        }
        
        
        _lifeRoutine = StartCoroutine(LifeRoutine());
    }
    
    private IEnumerator LifeRoutine()
    {
        yield return new WaitForSeconds(lifeTime);
        gameObject.SetActive(false);   // returns to the pool
    }
}
