using UnityEngine;
using UnityEngine.AI;

public class PlayerController : MonoBehaviour
{
    [SerializeField] Transform Target;
    [SerializeField] float Speed = 6f;
    [SerializeField] float AngularSpeed = 6f;

    [SerializeField] float DistanceThreshold = 0.2f;
    [SerializeField] float SlowDownThreshold = 1f;

    private void Awake()
    {
        Target.position = transform.position;
    }

    private void Update()
    {
        Vector3 dir = Target.position - transform.position;

        if (dir.sqrMagnitude < DistanceThreshold) return;

        float angle = Vector3.SignedAngle(transform.forward, dir, Vector3.up);
        float w = Mathf.Clamp(dir.magnitude, DistanceThreshold, SlowDownThreshold);
        w = map(w, DistanceThreshold, SlowDownThreshold, 0, 1);

        transform.Rotate(Vector3.up, angle * Time.deltaTime * AngularSpeed, Space.World);
        transform.Translate(transform.forward * Speed * w * Time.deltaTime, Space.World);
    }

    float map(float s, float a1, float a2, float b1, float b2)
    {
        return b1 + (s - a1) * (b2 - b1) / (a2 - a1);
    }
}
