Problem with rotations and quaternions

I have this script which run until the transform reaches a specific vector3 (positionTarget) which looks like this:

    private void Update()
    {

        if (Vector3.Distance(transform.position, positionTarget) > 0.01f)
        {
            var newPosition = (positionTarget - transform.position).normalized;
            transform.position = transform.position + newPosition * Time.deltaTime * speed;
        }
    }

Easy enough, now I’m trying to figure out how to write the same behavior for rotation. I know this script doesn’t make any sense and doesn’t work but here’s one of the many variations I have tried. (Just to represent the idea)

            if (Vector3.Distance(rotationTarget.eulerAngles, transform.rotation.eulerAngles) >/ 0.01f)
            {

                var newRotation = (rotationTarget.eulerAngles - transform.rotation.eulerAngles).normalized;
                transform.rotation = transform.rotation + newRotation * Time.deltaTime * speed;

            }

Here the rotationTarget is: [SerializeField] Quaternion rotationTarget;

I had this script for rotation before, but the thing is, I don’t want to use Lerp. I want a constant speed.

if (rotationFraction < .99f)
            {
                rotationFraction += lerpSpeed * Time.deltaTime;
                rotationFraction = Mathf.Clamp01(rotationFraction);
                transform.rotation = Quaternion.Lerp(transform.rotation, rotationTarget, rotationFraction / 60f);
            }

Can anyone point me in the right direction? I really would like to understand how to script the rotation behavior like the position. Here the pseudo code:

If (the difference between the current rotation and the target rotation is greater than “super small amount”)
rotate to the target rotation at constant speed;

Lerp does do a constant speed when you do it properly (that’s why it’s called a linear interpolation).

But you can also use Quaternion.RotateTowards to get a linear interpolation pretty simply:

if (Quaternion.Angle(rotationTarget, transform.rotation) > 0.01f)
{
   transform.rotation = Quaternion.RotateTowards(transform.rotation, rotationTarget, TIme.deltaTime * speed);
}
1 Like

Oh thanks PraetorBlue! I had tried this condition, but I didn’t know about Quaternion.RotateTowards. This is great! Works like a charm!