# Thread: rotating to a target direction

1. ## rotating to a target direction

I have an object defined with x,y, and th, right? What I want to be able to do is point to another location and have the object turn until it's pointing towards that location in the shortest way possible. So far I've come up with:
Code:
if(th < targetth)
th += dth;
if (th > targetth)
th -= dth;
The problem with this is that when the target location goes across the positive y access the object spins all the way around the other way. How can I have it reach the targetth in the shortest possible distance every time?

2. Something along the lines of
Code:
dir = 1;
if( th - target_th > 180 ) dir = -1;

if(th < targetth)
th += dth * dir;
if (th > targetth)
th -= dth * dir;
If the angle difference is greather then 180, go the oppisite direction you would normally go.

Need to toss in an ABS() some where in there.

3. Don't use euler angles. Euler's suffer from this problem in that it is not easy to rotate from say 345 degrees to 0 w/o the code causing the object to rotate in the direction of 270, or left, to get to 0 instead of simply choosing to rotate right.

You can test for this if you are using exact euler values but things get tricky when you start using matrices and other representations. I would suggest looking up quaternions.

Incidentally there is a thread on here about how to rotate to face a vector or point in space. D3DXMatrixLookAtLH and D3DXMatrixLookAtRH are what they are in Direct3D, but you can also derive them yourself.