using UnityEngine;
using System.Collections;

public class SpriteAnimation : MonoBehaviour {
	public int colCount = 4;
	public int rowCount = 1;
	public int rowNumber = 0;
	public int colNumber = 0;
	public int totalCells = 4;
	public int fps = 5;
	public Vector2 offset;
	public bool runsOnce = true;
	private int lastCol = 0;
	private bool running = false;
	
	public void Pause(){
		running = false;
		lastCol = colNumber;
	}
	
	public void Play(){
		running = true;
	}
	
	void setSpriteAnimation(int colCount, int rowCount, int rowNumber, int colNumber, int totalCells, int fps){
		int index = (int)Time.time * fps;
		index = index % totalCells;
		Vector2 size = new Vector2(1.0f / colCount, 1.0f / rowCount);
		int uIndex = index % colCount;
		int vIndex = index / colCount;
		offset = new Vector2((uIndex + colNumber) * size.x, (1.0f - size.y) - (vIndex + rowNumber) * size.y);
		renderer.material.SetTextureOffset("_MainTex", offset);
		renderer.material.SetTextureScale("_MainTex", size);
		if(runsOnce && index == colCount - 1)
			Pause();
	}
	
	public bool isPlaying(){
		return running;
	}
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if(running)
			setSpriteAnimation(colCount,rowCount,rowNumber,lastCol,totalCells,fps);
	}
}
