I was playing around, having fun, creating my own vector class, and the need to normalize it arose, I wrote a property and a function, the same as Unity, then I printed the result in the console and compared it with a vector with the same values but normalized by Unity’s functions, the numbers were off, my result threw something similar to 0.707, while Unity’s threw a rounded 0.71, for the value X of both vectors.
At first, I thought Unity was using fast inverse square root, so I tried that out, and the result was off again and by much more than the first time.
Here’s the code for the inverted square root:
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = BitConverter.SingleToInt32Bits(x);
i = 0x5f3759df - (i >> 1);
x = BitConverter.Int32BitsToSingle(i);
x = x * (1.5f - xhalf * x * x);
return x;
}
What really caught my eye is that there’s a warning in Unity’s API on the Vector.magnitude
page that says that you should use sqrMagnitude
instead since magnitude uses a square root operation, yet there’s no warning on the normalize
or Normalized
pages.
Does anyone have any idea how Unity normalizes vectors, or if there is a way to normalize a vector without using a square root? I wasn’t able to find anything on the net, and I’ve been searching for 3 hours or so.