The following two lines, in Update(), ensure that my Transform will always face along a forward direction (this.Point.forward) at a set angle of rotation (this.Rotation, a float ranging 0 - 360) around that forward axis.
this.transform.rotation = Quaternion.AngleAxis(this.Rotation, this.Point.forward);
this.transform.rotation = Quaternion.LookRotation(this.Point.forward, this.transform.up);
However, for reasons, now I want to smooth/lerp the rotation; so instead of setting ‘this.transform.rotation’ directly, I add a ‘targetRotation’ property to the class and change those lines to;
targetRotation = Quaternion.AngleAxis(this.Rotation, this.Point.forward);
targetRotation = Quaternion.LookRotation(this.Point.forward, this.transform.up);
And add;
this.transform.rotation = Quaternion.Slerp(
this.transform.rotation,
targetRotation,
this.rotationSpeed * Time.deltaTime
);
The (obvious) issue with the change is that the second assignment of targetRotation replaces the first.
I am unsure how to combine the Quaternion operations in a way that replicates what happens when I set the transform’s rotation directly.
I tried multiplying them, but that causes the rotation to spin faster-and-faster rather than just sticking to the value of this.Rotation.
Thanks!
First, rotate global up by the rotation around this.Point.forward
. You can use a *
operator to do this:
Vector3 upDir = Quaternion.AngleAxis(this.Rotation, this.Point.forward) * Vector3.up;
Then with that rotated up, proceed as before:
targetRotation = Quaternion.LookRotation(this.Point.forward, upDir);
this.transform.rotation = Quaternion.Slerp(
this.transform.rotation,
targetRotation,
this.rotationSpeed * Time.deltaTime
);
And by the way, using Lerp/Slerp functions with a t
that is never guaranteed to equal or exceed 1 can be error prone due to rounding errors if you need a guarantee that the output will eventually exactly equal the target.
If that guarantee is not necessary, this answer here is fine.
If that guarantee is necessary, consider using something else (e.g., rotateTowards
) instead of Slerp
.