# Vector3 precision issue?

What I want to do is reverse the rotation on my object until it is facing in the opposite direction to its movement (basically, turn the thing around so it's looking at the space it's passing) and then stop the rotation. Now, this code does work in terms of returning the correct values, as demonstrated by the print line's output to the log, but the 'if' statement never fails to run, even if the values match. I'm assuming there's some kind of extra precision used on the internal values which is clipped when sending the numbers to the log. If that's the case, how do I get a match for these values? I can't use mathf.round without first multiplying by 10 (which seems like overkill) since these values lie between -1.0 and 1.0. Is there another way?

``````playerdir=transform.forward; // Set on AddForce to grab direction of movement

if(Input.GetAxis("Vertical")<0) { // Down key
if (transform.forward!=Vector3(0-playerdir.x,0,0-playerdir.z)) {
transform.Rotate (0,0-(rotationspeed*Time.deltaTime),0);
print(transform.forward+" "+Vector3(0-playerdir.x,0,0-playerdir.z));
}
}

``````

Print the individual X/Y/Z elements of the Vector3 to see what they are without the rounding you get when printing the entire thing. It's almost impossible that the transform.forward would exactly equal the Vector3 that you're comparing it to; try using a range instead.

However, it doesn't seem like that would actually work anyway; if you use

``````var wantedRotation = Quaternion.LookRotation(-rigidbody.velocity);

``````

then that would give you a rotation of the opposite direction of movement, which you could then rotate towards with Quaternion.Slerp.

Edit: like this...

``````if (Input.GetAxis("Vertical") < 0.0) {
var wantedRotation = Quaternion.LookRotation(-rigidbody.velocity);
var angle = Quaternion.Angle(wantedRotation, transform.rotation);
var t = (1.0/angle) * Time.deltaTime * rotationSpeed;
transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, t);
}

``````

Found a solution that works for me. This lets me turn the ship using its rotation speed value measured over time, letting go of the key stops the rotation, and it picks the shortest route when deciding which way to turn. The 2 variance was necessary to overcome the thing skipping right over 180 but it's more than accurate enough.

``````playerdir=transform.rigidbody.velocity; // record vector of movement

if(Input.GetAxis("Vertical")<0) { // reverse
if(Mathf.RoundToInt(Vector3.Angle(playerdir,transform.forward))<178) { // 2 variance
rotation = rotationspeed*Time.deltaTime;
var angle1 = Vector3.Angle(transform.right, playerdir);
var angle2 = Vector3.Angle(-transform.right, playerdir);
if(angle1>angle2) { // find shortest route left/right
transform.Rotate (0,rotation,0);
} else {
transform.Rotate (0,0-rotation,0);
}
}
}

``````