Tuesday, 10 June 2008

Always compare the squares of the lengths.

And old trick but a good one. If you're trying to find out if a vector is over or under a certain length, then you don't need to do a whole GetLength on it, you can instead use GetSquaredLength, which doesn't include the sqrt function call. All you need to do then is compare it against the squared comparison value to find the same answers as you would have done if you had used the normal length function.

But the title of this post should be "simple things you should know about vectors" because that's not the only trick I'm going to mention.

If you want to know if two vectors are facing away from each other, or if they are facing the same direction, then all you need to know is the sign of their dot product. If it's positive, then they are facing the same direction, if it's negative, they are facing opposite directions. if it's zero, then either one or both of the vectors is zero length, or the two vectors are facing 90 degrees to each other.

If you want to find out the angle for how far up or down a vector is looking, and you know it's a unit vector (that is a vector of length 1), just use the vertical component of the vector in an arcsin. For small values, the arcsin will be virtually the same as the ingoing vertical component, so you might find that the angle is simply "vec.y". Using a simple power series you will get really close without having to do any arcsin at all for reasonable values of the vertical component.

angle = x - x^3/6 + x^5/120

this series will be accurate almost all the way to 45 degrees. Subtract x^7/5040 and you will be accurate to 90 degrees.

No comments: