Reputation: 255
I'm trying to flip my first person character smoothly while being able to rotate the player in y-axis using mouse look. The problem is the lerp does not end with an exact result. I want the ending rotation result to be exact such that (transform.up == TargetUpDirection())
void FixOrientation() {
if(transform.up != TargetUpDirection()) //Vector3(0, -1, 0)
{
transform.rotation =
Quaternion.Lerp(transform.rotation,
Quaternion.LookRotation(transform.forward,
TargetUpDirection(), 0.1f);
}
}
if I use mouse look while it flips, transform.up.y always result with less than 1 like for example 0.99881231 and I need to keep using mouse look until it corrects itself and I don't like it.
The cause is probably that when I use mouse look, the character forward gets modified which is causing this but I don't know how to implement a solution because quaternions confuses me.
Upvotes: 0
Views: 2065
Reputation: 20249
It's because as written, Lerp
is always rotating you 10% of the way remaining. This means that as you approach the target rotation, the amount by which you are rotated will decrease. Eventually, it will decrease to a point where rounding errors make you rotate by 0 degrees, before you actually arrive at the destination.
In most cases, you do not want to call Lerp
with a constant value for t
.
Here is an alternative. First, pick a maximum rotational speed:
float smooth = 5f;
Then, use Quaternion.RotateTowards
:
Quaternion targetRotation = Quaternion.LookRotation(transform.forward, TargetUpDirection());
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation , smooth * Time.deltaTime);
This answer was based off this post on the Unity forums.
Upvotes: 3