using UnityEngine;
using System.Collections;

public class spriteTalk : MonoBehaviour {
	private SpriteRenderer spriteRenderer;

	public Sprite[] sprites;
	public float framesPerSecond;
	// Use this for initialization

	
	public AudioClip grind;
	public bool playsound = false;




	void Start () {
		spriteRenderer = GetComponent<Renderer>() as SpriteRenderer;
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.LeftArrow)) {
			
			if (playsound == false) {
				playsound = true; 
				InvokeRepeating ("PlaySound", 0.2f, 0.8f);
				
			}
			

			
			int index = (int)(Time.timeSinceLevelLoad * framesPerSecond);
			index = index % sprites.Length;
			spriteRenderer.sprite = sprites [index];
			
		} else {
			
			
			spriteRenderer.sprite = sprites[0];
			
			
		}


		if (Input.GetKeyUp (KeyCode.LeftArrow) || Input.GetKeyUp (KeyCode.RightArrow)) {
			CancelInvoke("PlaySound");
			playsound = false;
		}
		
	}



	void PlaySound () {
		GetComponent<AudioSource>().PlayOneShot(grind, 0.5f);
		
	}
	}

