using UnityEngine;
using System.Collections;

public class StalkPlayer : MonoBehaviour {

    public float MaxTurnSpeed = 1.2f;
    public Vector2 CenterOfMass = Vector2.zero;

    Rigidbody2D r2;
    Transform player;

	void Start () {
        player = GameObject.Find("Player").transform;
        r2 = GetComponent<Rigidbody2D>();
        if (CenterOfMass != Vector2.zero)
            r2.centerOfMass = CenterOfMass;
	}
	
	void FixedUpdate () {
        TurnTowardPlayer();
	}

    private void TurnTowardPlayer()
    {

        float dx = player.position.x - transform.position.x;
        float dy = player.position.y - transform.position.y;
        float aimangle = Mathf.RoundToInt(Mathf.Atan2(dx, dy) * -180 / Mathf.PI);

        float off = Mathf.DeltaAngle(r2.rotation, aimangle);
        if (Mathf.Abs(off) <= 0.1f)
            return;

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

        r2.MoveRotation(r2.rotation + rot);
    }
}
