0

I'm trying to compare two values in C#, however I'm getting a weird result.

Here it goes:

 //Getting the pre-defined rotation value - 45 , 0 or 315 degrees as a float
 float rot = GetComponent<Transform>().rotation.eulerAngles.z;


        Debug.Log(rot.ToString());

        if (rot == 45)
        {
            Debug.Log("IN 45");
            GetComponent<Rigidbody2D>().velocity = new Vector3(2f, -bulletSpeed, 0);
        }
        else if (rot == 315)
        {
            Debug.Log("IN 315");
            GetComponent<Rigidbody2D>().velocity = new Vector3(-2f, -bulletSpeed, 0);
        }
        else
        {
            Debug.Log("IN 0");
            GetComponent<Rigidbody2D>().velocity = new Vector3(0, -bulletSpeed, 0);
        }

Now the weird behavior is as follows:

When rot is equal to 315, the result will go in the 2nd if statement, however when rot is equal to 45 (which is shown by the Unity Console tab), the result will enter the 3rd if statement instead of the 1st.

Now if i convert the first statement from a float "rot" compared with int "45" to string "Value of Rot" compared with string "45", the function works as intended.

Any insights on this.

Nassif Bousaba
  • 386
  • 1
  • 4
  • 22
  • Yes, the value isn't exactly 45, it's very close to it which makes the debugger show only 45 – Lasse V. Karlsen Jul 25 '18 at 17:11
  • @LasseVågsætherKarlsen , i thought of that, but when you transform it to a string, why does it take it as 45 and not like the exact value? - Additionally why is it working for 315? I tried different values 30 and 330, same thing occurs.. – Nassif Bousaba Jul 25 '18 at 17:15
  • It probably does something similar to what the debugger does. In any case, you should do a "close enough" comparison, like this: `if (Math.Abs(rot-45) <= 1e-5) ...`, and pick the correct value there to be "as low as this is counted as nothing", for your case. – Lasse V. Karlsen Jul 25 '18 at 17:20
  • You can also try `.ToString("G17")` as this will use "round trip" formatting and give you all the precision the number currently has. – Lasse V. Karlsen Jul 25 '18 at 20:46
  • @LasseVågsætherKarlsen i used the lower bounds method, thank you – Nassif Bousaba Jul 28 '18 at 17:13

0 Answers0