Floating Point Error?
Hi! I'm making a game in unity 2D and I'm having a floating point issue. I have an object that I want to shift down .2f for every input of its button. but the inspector window when I test it, I notice a problem: For reference, the code is: if (Input.GetKeyUp(KeyCode.Keypad0)){ gameObject.transform.position -= new Vector3(0f, .2f, 0f); }
So if the object starts at a Y of 6f, these are the Y positions: 6 5.8 5.6 5.400001 5.200001 5.000001 etc, then 0.600001 0.400001 0.200001 1.221895e-06
Why does it do this? It's position in the game is, I assume, 0.000001, but then why does Unity think it is at the given space? I'm just frustrated and would love some help on what I can do to fix this or a better way to go about it that is more reliable. I need to keep track of its position and have things happen at certain coordinate values. Thanks in advance! :D
There are many explanations of floating point already; could you the C# round to decimal precision function?
Answer by cjdev · Aug 25, 2015 at 02:48 AM
The problem is floating point imprecision. To get around it you can use Mathf.Approximately(float1, float2);
. Also, Unity basically does the same thing behind the scenes for Vectors when you use the default comparison for them so you're covered there.
I think my main concern is why does the float point change the displayed value so drastically when at or crossing the Y-axis? Especially when the number it is saying isn't the position the object is actually at
@tokyoscarab please do not post a comment or follow-up as an Answer; I converted this one for you.
What would be a good example of using that comparison in the application I am trying to make?
You could use it to compare two Y positions for instance to check for equality even though they have those extra decimal places.
Your answer
Follow this Question
Related Questions
C# function with multiple float arguments not working 1 Answer
For loop comparing two different objects appears to not be running 1 Answer
Having trouble teleporting player in a 2D game 0 Answers
Need 2D help - Want to have object move towards point when it touches a trigger. 0 Answers
Moving in Y and X after collision 0 Answers