using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Jump : EntityBehaviour
{
	public float duration;

	Vector3 oldPos, newPos;
	Quaternion oldRot, newRot;
	Vector3 centerOfMass;
	float initVelocity;
	bool jumping = false;
	float time;

	public void JumpTo(Vector3 pos, Quaternion rot) {
		Rigidbody body = GetComponent<Rigidbody>();
		centerOfMass = body.centerOfMass;

		jumping = true;
		time = 0;
		oldPos = transform.TransformPoint(centerOfMass);
		oldRot = transform.rotation;
		newPos = pos + rot * centerOfMass;
		newRot = rot;

		// Work out the parabola we need to follow to land here:
		float heightDiff = newPos.y - oldPos.y;
		float accel = Physics.gravity.y;
		initVelocity = (heightDiff - 0.5f*accel*duration*duration) / duration;
	}

	void Update()
    {
		if (jumping) {
			time += Time.deltaTime;
			if (time >= duration) {
				time = duration;
				jumping = false;
			}

			// Lerp everything across to the new point.
			float t = time/duration;
			Vector3 pos = Vector3.Lerp(oldPos, newPos, t);
			Quaternion rot = Quaternion.Slerp(oldRot, newRot, t);

			// Vertical motion follows a parabola under gravity.
			float accel = Physics.gravity.y;
			float y = initVelocity*time + 0.5f*accel*time*time;
			pos.y = oldPos.y + y;

			transform.SetPositionAndRotation(pos - rot*centerOfMass, rot);
		}

		if (!jumping) {
			StopAction();
		}
    }
}
