using UnityEngine;
using System.Collections;

public class CharacterAnimation : MonoBehaviour
{
	public string animationName;
	public float frameSpeed;

	private float frame;
	private Rigidbody2D rigidThing;

	// Use this for initialization
	void Start ()
	{
		rigidThing = GetComponent<Rigidbody2D> ();
		frame = 0f;
	}
	
	// Update is called once per frame
	void Update ()
	{
		
		if (rigidThing.velocity != Vector2.zero) {
			transform.rotation = Quaternion.EulerAngles (0f, 0f, MathHelper.getVectorAngle(rigidThing.velocity) - (Mathf.PI / 2f));

		}

		updateFrame ();
	}
	
	void updateFrame()
	{
		Sprite[] walkSprites = Resources.LoadAll<Sprite> ("Animations/" + animationName);
		if (rigidThing.velocity == Vector2.zero)
		{
			frame = 0f;
			GetComponent<SpriteRenderer> ().sprite = walkSprites [2];
		}
		else
		{
			frame += Time.deltaTime * frameSpeed * 15f;// * rigidThing.velocity.magnitude;
			GetComponent<SpriteRenderer> ().sprite = walkSprites [(((int)frame) + 3) % walkSprites.Length];
		}
		
	}
}
