For my RTS game's physics engine, I'm trying to find out a clever way to make a unit face the direction it's moving in. Given a Vector2d direction of movement (its normalized velocity), how can I calculate the unit's rotation? If possible, I'd rather not use inverse trig functions because I only have a lookup table for Sine.

  • \$\begingroup\$ You shouldn't use a rotation angles. They really are a bad representation of directions. If you choose to do so, you will need an inverse trig function. \$\endgroup\$ – user41442 Mar 31 '15 at 3:24
  • \$\begingroup\$ I've changed my system to not have a rotation variable for units but instead just make them face the direction of movement. I still need to calculate an angle from the Vector2d direction to rotate the vertices of the unit's collider. \$\endgroup\$ – JPtheK9 Mar 31 '15 at 3:36
  • 1
    \$\begingroup\$ You don't need angles, just vec2's which point in the represented direction and are unit length. Instead of storing theta, store the pair (sin(theta), cos(theta)). Almost all ops you could do with angles can be done better with this representation. \$\endgroup\$ – user41442 Mar 31 '15 at 3:59
  • \$\begingroup\$ That's perfect! Thanks! Do you mind posting that as an answer so I can accept it? \$\endgroup\$ – JPtheK9 Mar 31 '15 at 4:04

You shouldn't use a rotation angles if you can avoid it.* They are a bad representation of directions. If you choose to use them, you will need an inverse trig function.

Instead of storing theta, store the pair (cos(theta), sin(theta)). You can combine rotations and directions using the multiplication rules of complex numbers, i.e.

(a,b) * (c,d) = (ac - bd, ad + bc)

The 2D rotation matrix is easily constructed, because cos and sin of the angle are immediately available. Be sure to re-normalize the directions sufficiently often or they will inadvertently scale your points.

Finally, the angle between two vectors can be compared to a reference angle theta_0 using the dot product between the two direction vectors, as when the smaller angle between A and B is less than theta_0 iff cos(theta_0) < dot(A,B).

* Except for input/output to humans or as a compact way to store a direction if every byte counts.

  • \$\begingroup\$ A followup on this answer: To rotate the rotation vector but not use any trig (since that's probably why you're using a rotation vector), check this out: math.stackexchange.com/questions/1213991/…. \$\endgroup\$ – JPtheK9 Apr 1 '15 at 23:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.