Advertisement

Shortest rotation from one direction to another

Started by May 24, 2002 05:31 AM
2 comments, last by Gherkin 22 years, 8 months ago
I have the following math problem; Say I have direction D1 in radians (0 - pi*2) and another D2, and I want to check what direction I should rotate D1 to, so that it takes the shortest rotation towards D2. Like when you have a character standing, and it must rotate to look in a different direction... what is the shortest direction it should rotate?
In 2D...

Assuming positive angles mean clockwise movement and negative angles mean counter-cw movement, then "d = d1 - d2". If "d > pi" then "pi - d" is now the angle you want to rotate through, elsewise, "d" is the angle you want. Now you just divide "d" by the number of ticks you want to spent rotating, and that gives you the angle to rotate by each tick.

In 3D...

This is less trivial. The easiest way to do it is to use a quaternion (which you can read about in the articles section, here). However, using a quaternion causes rotations around all the axes, not just X and Y: if you have a direction you want to face in, then although quaternions will make the object point the right way, it will also result in rotations around the Z axis. I haven''t been able to precisely figure out a way to rotating to face a particular point using only X and Y rotations (my methods tend to fail under unexpected circumstances).
CoV
Advertisement
Presumably this is in 2D, as in 3D you need a vector to specify a direction.

Then just calculate D2 - D1. This will result in an angle A, between -2pi and 2pi. If A > pi subtract 2pi from it. If A < -pi add 2pi from it (adding or subtracting 2pi gives you the same rotation).

You now have an angle, A, between -pi and pi. If A < 0 you need to turn in the direction of decreasing angles, e.g. clockwise. If A > 0 you turn anticlockwise. Code for this would look something like.

A = D2 - D1;
if (A > pi) A -= 2 * pi;
if (A < -pi) A += 2 * pi;
if (A > 0)
{
// set turn direction to anticlockwise
}
else
{
// set turn direction to clockwise
}
John BlackburneProgrammer, The Pitbull Syndicate
OMG, that is so simple! Didnt even thought about that! (/me was trying with dot product and stuff)

I see the light now, thanx people!




Pascal vd Heiden
XODE Multimedia

This topic is closed to new replies.

Advertisement