Hi All, I have a simple enough scenario which is presenting unexpected results. I am comparing a float with an int multipled with a float. Both the values are equal to 2 but the if statement doesn't think this is the case. Code (CSharp): private int leftLane = -1; private int centreLane = 0; private int rightLane = 1; public float laneWidth = 2.0F; Later on in the function I move an object towards a lane and want to disable input while this is happening. Code (CSharp): bool IsInLane(){ var currentLane = transform.position.x; if (currentLane == rightLane * laneWidth) { return true; } return false; } You can see from my Immediate window in the debugger that the function should have returned true? Can anyone explain this to me please?
No I'm not snapping to a grid. The if statement shoulnd't need to be snapped to anything it should just be comparing two values of type float though?
I'm going to guess that it's a precision problem. float*int returns a float, which probably isn't an exact number (eg. 1.00000000001) which in your case will fail the comparison. Just a guess.
You should (almost) never test whether two floating point numbers are equal. Instead, test whether they are within some threshold of each other. So, instead of writing Code (CSharp): float x, y; // Code if (x == y) use something like Code (CSharp): const float epsilon = 1e-5; float x, y; // Code if (Math.Abs(x-y) < epsilon)
So I have replaced my compare statement with Mathf.Approximately() and it has done the trick. The problem here wasn't the fact that I shoulnd't have been comparing two floating point numbers, but the fact that the debugger and the immediate window aren't accurate representations of the floats. Thanks for the help folks