using UnityEngine;
using System.Collections;

public class Animation : Sprite2D
{
    public float fps = 24f;
    public int repeatCount = 1;
    public bool isLoop = false;

    int _currentIndex;

    void Start()
    {
        _currentIndex = 0;
        StartCoroutine(DoAnimate());
    }

    IEnumerator DoAnimate()
    {
        while (true)
        {
            yield return new WaitForSeconds(1 / fps);

            Vector2 newLowerLeft = spriteLowerLeft + new Vector2(spriteSize.x, 0f) * _currentIndex;
            _mesh.uv = new Vector2[]{
	            new Vector2(1f/texWidth * newLowerLeft.x, 1f-1f/texHeight * newLowerLeft.y),
				new Vector2(1f/texWidth * newLowerLeft.x, 1f-1f/texHeight * (newLowerLeft.y - spriteSize.y)),
				new Vector2(1f/texWidth * (newLowerLeft.x + spriteSize.x),
					1f-1f/texHeight * newLowerLeft.y),
				new Vector2(1f/texWidth * (newLowerLeft.x + spriteSize.x),
					1f-1f/texHeight * (newLowerLeft.y - spriteSize.y))
	        };

            if (_currentIndex >= repeatCount)
            {
                _currentIndex = 0;
                if (!isLoop)
                    break;
            }
            else
                _currentIndex++;
        }
    }
}