/* Spencer Park
 * GAM 215_01
 * Week 04
 * Created: 2017/03/08
 * Last Edit: 2017/03/08
 * */

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour
{

	public static CameraShake instance;

	private Vector3 _originalPos;
	private float _timeAtCurrentFrame;
	private float _timeAtLastFrame;
	private float _fakeDelta;

	void Awake()
	{
		instance = this;
		_originalPos = instance.gameObject.transform.localPosition;
	}

	void Update()
	{
		// Calculate a fake delta time, so we can Shake while game is paused.
		_timeAtCurrentFrame = Time.realtimeSinceStartup;
		_fakeDelta = _timeAtCurrentFrame - _timeAtLastFrame;
		_timeAtLastFrame = _timeAtCurrentFrame;
	}

	public static void Shake(float duration, float amount)
	{
		instance._originalPos = instance.gameObject.transform.localPosition;
		instance.StopAllCoroutines();
		instance.StartCoroutine(instance.cShake(duration, amount));
	}

	public IEnumerator cShake(float duration, float amount)
	{
		//float endTime = Time.time + duration;

		while (duration > 0)
		{
            Vector3 rando = Vector3.zero;
            rando.x = Random.Range(-amount, amount);
            rando.y = Random.Range(-amount, amount);
            transform.localPosition = _originalPos + rando;

			duration -= _fakeDelta;

			yield return null;
		}

		transform.localPosition = _originalPos;
	}
}