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

public class SeekTarget : MonoBehaviour
{
    public GameObject target;
    public Rigidbody rb;
    public float maxSpeed = 1f;
    public float maxForce = 1f;
    //public float turnSpeed = 1f;

    void FixedUpdate()
    {
        

        // alternate way to rotate (with added turnSpeed control)
        //var rotation = Quaternion.FromToRotation(Vector3.forward, targetDir.normalized);
        //var ip = Mathf.Exp(-turnSpeed * Time.deltaTime); // better turn speed control
        //transform.rotation = Quaternion.Slerp(rotation, transform.rotation, ip);

        // Using forces isn't 
        //add force, combining current forward direction with direction of target
        //var targetDir = (target.transform.position - transform.position);
        //rb.AddForce(transform.forward + targetDir);

        // clamp to maxSpeed
        //rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
    }

    void SeekWithPhysics()
    {
        var targetDir = (target.transform.position - transform.position);

        //alternate way to rotate(with added turnSpeed control)
        var rotation = Quaternion.FromToRotation(Vector3.forward, targetDir.normalized);
        var ip = Mathf.Exp(-2f * Time.deltaTime); // better turn speed control
        transform.rotation = Quaternion.Slerp(rotation, transform.rotation, ip);

        // add the force
        rb.AddForce(transform.forward + targetDir);

        //clamp velocity to maxSpeed
        rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);

    }

    void Seek()
    {
        // Seeking -- not sure if this is actually working
        // Navagents are probably a better choice in this case ... unless you need to avoid the navmesh

        // get direction of the target
        var desired = (target.transform.position - transform.position);
        // calc steering direction
        var steering = desired - rb.velocity;
        // limit the steering force
        //steering = Vector3.ClampMagnitude(steering, maxForce);

        //var velocity = Vector3.ClampMagnitude(steering + rb.velocity, maxSpeed);
        var velocity = steering + rb.velocity;

        // move to the new position based on this velocity
        rb.MovePosition((transform.position + velocity) * Time.deltaTime);

        // rotate toward the target
        transform.LookAt(target.transform);
    }
}
