0
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\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
    Commented Mar 31, 2015 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
    Commented Mar 31, 2015 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
    Commented Mar 31, 2015 at 3:59
  • \$\begingroup\$ That's perfect! Thanks! Do you mind posting that as an answer so I can accept it? \$\endgroup\$
    – JPtheK9
    Commented Mar 31, 2015 at 4:04

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\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
    Commented Apr 1, 2015 at 23:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .