Wednesday, January 24, 2007

Tip: Vector2.Normalize()

Vector2.Normalize() will fail silently if both members X and Y are zero. When it fails, the method will set X and Y to NaN (which stands for Not a Number.) Most operations using NaN will yield NaN so pretty soon all of your floating point values will become NaN!

When using Normalize() use the following pattern:

Vector2 delta = new
Vector();
if (delta
!=
Vector2.Zero)
{
delta.Normalize();
}


Or:


Vector2 delta = new
Vector();
if
(delta.LengthSquared > 0)

{

delta.Normalize();

}

You may be tempted to use the following because it is most "mathematically" correct:

Vector2 delta = new Vector();
if (delta.Length > 0)
{
delta.Normalize();
}

But don't do it! The Length property causes a square root operation which is really expensive.

Labels:

New Goal: XNA Hints and Tips

From now on I'm going to post XNA hints and tips as I come across them. The XNA platform enables garage developers to create games for Windows and Xbox360 for free. You can find more information here: http://msdn.microsoft.com/directx/XNA/default.aspx

Labels: