Friday, 6 June 2008

Vectors are cool, angles are not.

When you are learning about maths at school, you think that trigonometry will be the best thing ever to learn to help you code games. You get taught about sins and cosines, tangents and pi. These things seem like the way to go.

Once you've spent a little time working in a games company though you'll notice that no-one actually uses them for much. Why? Vectors can do almost anything an angle can do, and when they do, they cost a lot less.

One of the things I still see people doing on occasion is figuring out what angle something is at so that they can fire off and angle oriented event. An example of this would be an entity trying to align itself to face another entity. Vectors can do this really well, there is no reason to resort to nasty gimbal locking euler angles. If you take the vector that is the difference of the position of the target and the position of the thing that is trying to reorient, you can normalize that vector and find it's difference from your forward vector to quickly calculate an error vector, or multiply it by the inverse model matrix to get a localised direction vector. This new vector can be then used in a number of different ways to do the work.

P(thingy), T(target)

L = T-P

error = L - P.forward
local direction = L * P.inv

the error vector is a global space vector, useful for modifying an entity on a global scale.
the local direction vector is useful for working out what an entity has to do to itself to affect its orientation. This is really useful in flight sims and space games where there is no real "up", and gimbal lock would kill you.

Happy hacking.
Post a Comment