Hi,
I’ve been trying to turn my cube around but it seems like my if statement is leaving too much room for error.
When I’m still a little bit (like a real little bit that’s <0.1) away from the goal it still returns true…
If anyone could be of help that would be great!
Thanks in advance
Unity adds equality operator overrides for Vectors so they will be considered equal when they are very close. I can’t verify currently, but I would guess they’ve done the same thing for Quaternions, which would explain why they’re showing as equal when they’re not.
That said, if Unity wasn’t overriding equality then as others have said you would never/rarely get an equal value because of floating point rounding and such.
So Unity’s equality operator is probably doing what you want, but you may want to snap the rotation to the exact value once it compares as true.
Another option is to use Quaternion.Slerp properly. Any type of interpolation function expects the value t
to range from 0 to 1. You should have a variable that updates every frame that increments t
by Time.deltaTime
and clamps it between 0 and 1. You then know exactly when the rotation is done because t
will equal 1.
Simple Sample Code:
//Sry for Logic Function. replace bool with void and remove return statements to use in FixedUpdate
//Will have to use "* Time.deltaTime" to use in update ;) or how ever your gonna use it.
public bool FaceTarget() {
//where we want to look/aim. This calculation is seperated out to clean up code here....
Quaternion rotation = Quaternion.LookRotation (target - transform.position, Vector3.up)
if (transform.rotation != lookAtRotation ) {
transform.rotation = Quaternion.RotateTowards (transform.rotation, rotation,
rotationSpeed * Time.fixedDeltaTime); //Intended Rotation over time
return false;
} else {
transform.LookAt (target); //corrective "Snap" when "lined Up".
return true;
}
}
See @Dave-Carlile 's answer.
Quaternions hold values for X,Y,Z, and W as floats. It’s never a good idea to test equality with floating point numbers.
You will need to rewrite your conditionals keeping in mind that two Quaternions will never be exactly equal.