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?