- Home /
Box doesn't move to the position as I expect
Originally, I want to simplily move a box whose position just changes like (0,0,0)->(0,0,-1)->(0,0,-2), etc. In order to move it more realistic, I use a counter set as 50 and move the box (0,0,-0.02) and print the box's position every time FixedUpdate() called. The psuedo-code is as follows:
function FixedUpdate () {
if(can_move)
{
……//other code
}
if(count < 50)
{
Box_position += (dir/50);
Debug.Log(count+"box position now:“+Box_position.ToString("f8)));
count ++;
}
else
{
Box_position = Box_old_position + dir;
……//other code
}
}
}
The variant "dir" actually equals to (0,0,-1), so "dir/50" to (0,0,-0.02). The output image is as follows:
As we can see from the third to fifth figures after the decimal point in the image, it changed from "000" to "999" and then to "998"(not displayed in this image). Till now the box still move normally as I expected. However, after three times' move(50*3 for counter variant), the box's position suddenly changes abnormally when the counter is 42 in the fourth move like the image as follow
It suddenly changes from "998" to "001" to "007" and then to more big numbers in a "fast speed". In addition, the x-axis coordinates also changes abnormally because the dir's x-axis coordinates is 0.
I dont want to believe this is the Unity's problem, so can anyone tell me why?
Answer by robertbu · May 05, 2013 at 06:07 AM
Floating point numbers are imprecise. They are an approximation of real numbers and suffer from rounding errors. Given the significance of the digits you highlight, there is no practical difference between the positions used and the "perfect" position for most applications. For the most part, this is not a Unity issue. This problem occurs with any application that uses floating point numbers. The only Unity issue here is that Unity elected to go with the less precise 'float' values rather than the more precise 'double' values (for valid technical reasons).
yeah i know the floating point number are imprecies. and if it still gone from "000" to "999" to "998" in the fourth movement as the former three times, i think it will have no problems here. But it didnt happen as I expected in the fourth movement as the former three times, that's the problem.
As a result, in the former three times, the box's destination is always right as I expect for my assignment code
else
{
Box_position = Box_old_position + dir;
……//other code
}
But in the fourth movement, as I tested, after 50 times "short" movement and the last assignment for box's position in the above code, the box's position still have a litte floating-point change which I dont know how it happens because I dont have any other code to change the box's position except the above code in FixedUpdate(). This problem troubles me the most.