Friday, April 26, 2013

When is Normal not Normal?

Say you've got a vector that you want to normalize:-

Vector v = new Vector([a number], [another number]);
v.normalize();

What would you expect to happen if both your numbers (maybe the movement vector of your space invader) were 0?

I would hope it would return a vector of (0, 0), so that when you added this vector to your sprite's co-ords, it didn't move.  Which, with a vector of 0, 0, would be correct.

Unfortunately, in Android Java (and maybe normal Java as well), it returns (NaN, NaN), which is no use to anyone.  I'd prefer an error at least (failfast?) so that I knew something unexpected was happening.  With NaN, all your sums suddenly go awry, and until you know the above piece of information, you'll spend ages trying to work out just how your vector is turning into garbage and why your sprite has decided to move to infinity on both axis.

No comments: