Odd issue with Vector3

I have a vector3 I am using to determine direction. The vector3 is normalized.

I am having a strange thing happen with it. For the most part everything is fine, but when I move the character to the right side of the screen, something strange occurs with the normalized vector.

Looking at it in the inspector, or using debug.log to write out the vector, I see the expected (0, -1, 0) or whatever direction I am moving in. However, when I expand the vector3, the x value is a large negative scientifically notated number. Any idea what would cause this, and how to correct it?

Any help is appreciated!
-Larry

3608565--293263--Vector3 Problem.png

It is a floating point precision issue, and it is common. Notice that it is -1.9E-06, which is actually -0.0000019, which of course is very small. Negligible for all intents and purposes.

The problem it is causing me is the code I wrote to determine direction expects a 0 there, when moving up or down, and it is resulting in the moving left animation playing when moving up or down. I can adjust the code to correct for it, but it was just confusing the heck out of me why it was doing that in the first place. It only appears to do it, when my transform position moves to the right side of the screen.

-Larry

Always expect that floats could be not equal to exact number.
Don’t do == and use Mathf.Approximately() or do the .Abs() < Precision instead if that’s the case.

1 Like

Was just strange when it was working fine until I got the the right side of the screen, then went all wonky :slight_smile:

I have corrected for it in code, and everything is working as expected now, was just really confused :slight_smile:

Thank you both for your responses!

-Larry

Check that floats are within a range, don’t check that floats are exactly a specific number.

if (myFloat > -0.001f && myFloat < 0.001f)
{
    something();
}

You won’t necessarily see the effects of precision issues until a float gets a high enough value either positive or negative for accuracy errors to start showing up. Floats can record around 7 decimal places with high accuracy.