- Home /
LookRotation not working as expected when turning GameObject in direction of Velocity
I created a script to always keep a character facing its rigidbody.velocity
. Everything seems to work fine for the most part, until input stops and sometimes the character rotates to a seemingly random direction. The object is part of a hierarchy, however the parent object itself is not being rotated, only child objects. Therefore, this object should only be affected by the following code, which is called in Update
:
private void MatchRotationToVelocity()
{
Vector3 rotateTo = new Vector3(rigidbody.velocity.x, 0, rigidbody.velocity.z).normalized;
if (rotateTo != Vector3.zero)
{
meshModel.rotation = Quaternion.Slerp(meshModel.rotation, Quaternion.LookRotation(rotateTo), rotationSmoothTime);
lastFacingDirection = meshModel.rotation;
}
else
meshModel.rotation = Quaternion.Slerp(meshModel.rotation, lastFacingDirection, rotationSmoothTime);
}
The else statement shouldn't even be needed. The idea is that if there is no velocity, the object should maintain its current rotation. Any ideas why this isn't working as expected?
Answer by Bunny83 · Sep 05, 2021 at 08:13 AM
Well, your if statement doesn't really handle "no input" properly. First of all your velocity most likely is not completely 0 on all axis, unless the rigidbody actually starts sleeping. Before that the velocity may have a tiny rest offset. Since you normalize this vector, the vector will always have a length of 1 with the only exception when the velocity is really really small or equal (0,0,0) in which case "normalized" returns Vector.zero.
You should not normalize the velocity before your if statament. Also you probably want to have a minimum velocity threshold. Something like this:
Vector3 rotateTo = rigidbody.velocity;
rotateTo.y = 0f;
if (rotateTo.sqrMagnitude > 0.01f)
{
meshModel.rotation = Quaternion.Slerp(meshModel.rotation, Quaternion.LookRotation(rotateTo), rotationSmoothTime);
}
Note when using sqrMagnitude the threshold also need to be squared. So the actual min velocity limit is 0.1 when using 0.01
Keep in mind that LookRotation actually takes 2 arguments. When you don't provide an up vector, you will implicitly use Vector3.up as up vector.
Your answer
Follow this Question
Related Questions
Quaternion rotation issue 1 Answer
"Look rotation viewing vector is zero" error 2 Answers
LookRotation Between 2 Points 1 Answer
SmoothDamp from 360 to 1 1 Answer
Rotating a 2D sprite to face a target on a single axis. 3 Answers