﻿using UnityEngine;
using System.Collections;

namespace Nostalgia.Example
{
	[AddComponentMenu("Nostalgia/Example/MoveWall")]
	public sealed class MoveWall : MonoBehaviour
	{
		public Vector2 from;
		public Vector2 to;
		public float duration = 1.0f;
		public float beginTime = 0.0f;

		private float _BeginTime;
		private Vector3 _BeginPos;

		Rigidbody2D _Rigidbody;

		void Awake()
		{
			_Rigidbody = GetComponent<Rigidbody2D>();
		}

		void Start()
		{
			_BeginTime = Time.fixedTime - beginTime;
			if (_Rigidbody != null)
			{
				_BeginPos = _Rigidbody.position;
			}
			else
			{
				_BeginPos = transform.position;
			}
		}

		void FixedUpdate()
		{
			float t = (Time.fixedTime - _BeginTime) / duration;

			t = (Mathf.Sin(t) + 1.0f) / 2.0f;

			if (_Rigidbody != null)
			{
				Vector2 pos = _Rigidbody.position;
				pos = (Vector2)_BeginPos + Vector2.Lerp(from, to, t);
				_Rigidbody.MovePosition(pos);
			}
			else
			{
				Vector3 pos = transform.position;
				pos = _BeginPos + (Vector3)Vector2.Lerp(from, to, t);
				transform.position = pos;
			}
		}
	}

}
