- Home /
"Look rotation viewing vector is zero" error
I have some smooth look code that spams this error. It basically makes an object look in the direction a rigidbody is moving.
void Update()
{
if (target)
{
if (bSmooth)
{
Quaternion rotation = Quaternion.LookRotation((transform.position + target.rigidbody.velocity) - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation , smoothSpeed * Time.deltaTime);
}
else
{
transform.LookAt(transform.position + target.rigidbody.velocity);
}
}
}
The error is this line:
Quaternion rotation = Quaternion.LookRotation((transform.position + target.rigidbody.velocity) - transform.position);
Answer by flaviusxvii · Feb 11, 2013 at 05:42 PM
Basic arithmetic..
(transform.position + target.rigidbody.velocity) - transform.position
(A + B) - A = B
So if B is a zero length vector (no velocity), then the function LookRotation will be mad at you.
The common fix is to guard with "if velocity is not zero".
You want to say "if not moving, face the way I was before," and doing nothing accomplishes that.
Why doesn't it like it being zero? Shouldn't it just make the rotation (0,0,0)?. It's not even a proper warning/error, just a normal Print/Debug.Log. Anyway, here is the final piece of code, with a little extra to fix something specific to my game:
if (target.rigidbody.velocity != Vector3.zero)
{
Quaternion rotation = Quaternion.LookRotation((transform.position + target.rigidbody.velocity) - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, smoothSpeed * Time.deltaTime);
}
else
{
transform.rotation = Quaternion.Euler(Vector3.zero);
}
A zero length vector allows for an infinite number of "correct" rotations, ins$$anonymous$$d of just choosing one arbitrarily, or choosing some consistent default, Unity does the only sane choice, which is to assume you're not expecting undefined results, and throwing an error.
Answer by supamigit · Aug 12, 2015 at 04:18 PM
I got similar issue and it was to do with i didnt declare what the OBJECT tag was so it dodnt find the v3.look rotation.... Are u doing similar to find your object to mouse?
For those using Nav$$anonymous$$eshAgent
if (navAgent.desiredVelocity != Vector3.zero) { transform.rotation = Quaternion.LookRotation(navAgent.desiredVelocity); }
O$$anonymous$$G thank you, you just ended a 4hr headache for me D: