2

Closed

Vector.Normalize (bug with NaN values)

description

Hello!

In Common/Vector2 there is a method Normalize, which is not handling dividing by zero. It cause troubles like Nan positions, Nan linear velocities when two bodies are spawned at the same point.
I fixed it simple by adding this stuff (not elegant, but works)
        public static void Normalize(ref Vector2 value, out Vector2 result)
        {
            float factor;
            DistanceSquared(ref value, ref zeroVector, out factor);
            if (factor == 0)
            {
                result.X = -1;
                result.Y = -1;
            }
            else
            {
                factor = 1f / (float)Math.Sqrt(factor);
                result.X = value.X * factor;
                result.Y = value.Y * factor;
            }         
        }
Closed Aug 30, 2014 at 10:37 PM by genbox
The code comes from Mono. They copied the behavior of XNA, which returns float.NaN when you normalize zero length vectors. Either report this issue to Mono, or check if your vectors are zero length before normalizing them.

comments