using UnityEngine;
using System.Collections;

public class ShapeMovementController : MonoBehaviour {

    public float RecenterSpeed = 10f;
    public Vector2 CenterOfMass = Vector2.zero;

    public Vector2 Move;
    public float Rotate;
    public bool RecenterTrigger = false;
    private Rigidbody2D r2;

	void Start () {
        r2 = GetComponent<Rigidbody2D>();
        r2.centerOfMass = CenterOfMass;
	}
	
	void Update () {
    //        transform.position += (Vector3) Move;
        //transform.localEulerAngles += new Vector3(0, 0, Rotate);
        //if (Rotate != 0)
        //    Debug.Log("ShapeMovementController rotating " + Rotate + "  from (T)" + transform.localEulerAngles.z + ", (R)" + r2.rotation + " to " + (r2.rotation + Rotate));
        if (RecenterTrigger)
            Recenter();
        else
            r2.MoveRotation(r2.rotation + Rotate);
        r2.MovePosition(r2.position + Move);
	}

    private void Recenter()
    {
        RecenterTrigger = false;
        float off = Mathf.DeltaAngle(r2.rotation, 90);
        if (Mathf.Abs(off) <= 0.1f)
            return;

        float dir = off / Mathf.Abs(off);
        float rot = RecenterSpeed * dir;
        if (Mathf.Abs(off) < Mathf.Abs(rot))  // don't over-rotate
            rot = off;

        r2.MoveRotation(r2.rotation + rot);
        //Debug.Log("Recenter: angle " + transform.localEulerAngles.z + " off is " + off + ", dir " + dir + ", rot " + rot);

    }
}
