Quaternion Lerp when using a raycast.

Hello,

I have a Topdown game where I use my mouse pointer to make my character look into different directions. For that I use a racycast and the LookAt function, but I would like to add a turnspeed to my character so it’s not so snappy.

I have been looking into Quaternion.Lerp but each time I implement it on my code, my character just turns frenetically and in the wrong axis.

This is my basic code to look at my pointer

        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z));
        }

Is there a way I can use my hit.point to turn with Quaternion.Slerp?

This is the code I tried that makes my character just turn frenetically and also lie down instead of standing up.

    void PlayerRotation()
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            //transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z));
            Vector3 distance = hit.point - transform.position;
            distance.y = 0;
            Quaternion targetRotation = Quaternion.LookRotation(distance);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 1);
        }

Something like this should work. This is assuming your raycast is in Update(), but if its not you can set targetRotation anywhere as long as your Slerp call is in Update().

Quaternion targetRotation;
public float speed = 1f;

void Update () {

    //Other code

    if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
        
        targetRotation = Quaternion.LookRotation(hit.point - transform.position);        
    }

    //Other code 
    
    transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed*Time.deltaTime);
}