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

public class Chase : MonoBehaviour {

    public Transform target;
    public float turnSpeed;
	
	// Update is called once per frame
	void Update () {
        if (target == null)
        {
            var go = GameObject.FindWithTag("Player");
            if (go == null)
                return;
            target = go.transform;
        }
        transform.position = target.position;
        var targetRot = target.rotation.eulerAngles.y;
        var currentRot = transform.rotation.eulerAngles.y;
        var distanceCW = (targetRot - currentRot);
        while (distanceCW < 0) distanceCW += 360;
        while (distanceCW > 360) distanceCW -= 360;
        var distanceCCW = 360 - distanceCW;
        var rot = turnSpeed * Time.deltaTime;
        rot = Mathf.Min(new float[] { rot, distanceCW, distanceCCW });
        if (distanceCCW < distanceCW) rot = -rot;
        transform.Rotate(Vector3.up, rot);
    }
}
