unity – Why when setting the value of the variable backToOriginSpeed to high the head is rotating much backward?

``````using System.Collections;
using UnityEngine;

public class LookAtTarget : MonoBehaviour
{
public Transform target;
// Keep this low to make the tracking tight for small target movements.
public float lookChangeDuration = 0.1f;

// Use this to limit our top rotation speed when making a big turn.
// It's measured in "approximately" radians per second.
public float maxLookSpeed = 5f;
public float backToOriginSpeed;

Vector3 lookVectorVelocity;
Vector3 originalLookDirection;

Vector3 look;

private void Start()
{
originalLookDirection = transform.forward;
}

void LateUpdate()
{
Vector3 desiredLook = (target.position - transform.position).normalized;

if (Vector3.Dot(desiredLook, originalLookDirection) < 0)
{
look = Vector3.SmoothDamp(transform.forward,
originalLookDirection,
ref lookVectorVelocity,
backToOriginSpeed);
}
else
{
look = Vector3.SmoothDamp(transform.forward,
desiredLook,
ref lookVectorVelocity,
lookChangeDuration,
maxLookSpeed);
}

transform.rotation = Quaternion.LookRotation(look);
}
}
``````

I’m using the variable backToOriginSpeed to make the head smooth rotating back to it’s original rotation. It’s working fine on fast speed low values like 1 or 3 or even 4 but when setting the value of backToOriginSpeed to 7 or 12 the head is rotating backward and most of the time not even rotating back but catching the rotating target and rotate with it.

The idea is that if I set the backToOriginSpeed value to 7 or 12 or higher value the head will not pass the forward view and just will take it 7 or 12 speed to return back. if the target is rotating very fast it will catch the head in the middle but the backToOriginSpeed is not working for high values.

Update :

This is working perfect just like I wanted :

I’m not sure if this is the right way to do it but it’s working.

``````using System.Collections;
using UnityEngine;

public class LookAtTarget : MonoBehaviour
{
public Transform target;
public float duration;

Vector3 originalLookDirection;
Vector3 orig;
Vector3 lookVectorVelocity;
public float lookChangeDuration = 0.1f;
public float maxLookSpeed = 5f;

private void Start()
{
originalLookDirection = transform.forward;
orig = transform.rotation.eulerAngles;
}

private void LateUpdate()
{
Vector3 desiredLook = (target.position - transform.position).normalized;

if (Vector3.Dot(desiredLook, originalLookDirection) > 0)
{
var look = Vector3.SmoothDamp(transform.forward,
desiredLook,
ref lookVectorVelocity,
lookChangeDuration,
maxLookSpeed);

transform.rotation = Quaternion.LookRotation(look);
}
else
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(orig), duration * Time.deltaTime);
}
}
}
``````

With the Lerp part in the else I control the rotation back to the original rotation by duration.