Why the transform when looking at target is less rotating by angle on the right side ?

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

[RequireComponent(typeof(Animator))]

public class SmoothLookAt : MonoBehaviour
{
    public Transform lookObj = null;
    public float finalLookWeight;
    public float weightDamping = 1.5f;

    protected Animator animator;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    //a callback for calculating IK
    void OnAnimatorIK()
    {
        if (lookObj != null)
        {
            Vector3 flattenedLookAtVector = Vector3.ProjectOnPlane(lookObj.position - transform.position, transform.up);
            float dotProduct = Vector3.Dot(transform.forward, flattenedLookAtVector);
            float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
            finalLookWeight = Mathf.Lerp(finalLookWeight, lookWeight, Time.deltaTime * weightDamping);
            float bodyWeight = finalLookWeight * .5f;

            animator.SetLookAtWeight(finalLookWeight, bodyWeight);
            animator.SetLookAtPosition(lookObj.position);
        }
    }
}

There is a clamp but for some reason when the target object is on the left side(from my point of view) the transform is looking at it fine but when the target object is on the right side the transform is almost not looking at it if at all.

I want that the clamp will be equal for both sides.

Try getting the absolute value of the dot product instead of clamping it, since dot product is from -1 to 1.

float lookWeight = Mathf.Abs(dotProduct);
1 Like

In general it’s working but than the whole rotating of the player is much less smooth. It’s more sharp rotations than before. With the original line the rotation/s was more smooth.

What does Vector3.ProjectOnPlane mean ? If I have for example a terrain than it won’t work at all ?

finalLookWeight = Mathf.Lerp(finalLookWeight, lookWeight, Time.deltaTime * weightDamping);

The field, weightDamping seems to be 1.5, but any lerp weight values should be in between 0 and 1, 0 being smoother/slower and 1 being quick/jerky. Try setting the value of the third argument of Mathf.Lerp to be in between 0 and 1.

finalLookWeight = Mathf.Lerp(finalLookWeight, lookWeight, Time.deltaTime);

Or

[SerializeField, Range(0, 1)] private float weightDamping = 0.2f;
// Inside your method
finalLookWeight = Mathf.Lerp(finalLookWeight, lookWeight, weightDamping);

In general, when I use any Lerp methods, 0.1 - 0.2 works smoothly for me.