views:

125

answers:

3

I have a list of points with x, y coordinates. I know how to get the distance between points with sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2)) and the angle between points with atan2(y1 - y2, x1 - x2).

How can I calculate the relative angle between the points (left, right, straight)? So, if I'm at point 1, what is the relative direction to point 2, then 2 to 3, 3 to 4, etc...

Thanks for any help!

+1  A: 

Call atan2($y1 - $y2, $x1 - $x2)

If it's between π/2 and 3π/2, it's straight.
If it's more than 3π/2 or less than -3π/2, it's a left turn.
If it's between -π/2 and π/2, it's a right turn.

Here is a diagram:

 {3π/2}-------{π/2}-------{π/4}
      | +-----[ +y]-----+ | 
      | |               | | 
      | |               | | 
    {π} [-x]  [0,0]  [+x] {0} 
      | |               | | 
      | |               | | 
      | +-----[ -y]-----+ |
{-3π/2}-------{-π/2}------{-π/4}
SLaks
I'm already doing that. I just need to understand how to interpret the results, I guess...
aan234g
That's an angle in radians.
SLaks
Doesn't that assume you start facing between 3π/2 and π/2? If you started facing 0 then it's a whole different ball game. Assuming this is akin to a SatNav system then the turn direction can only be determined from x2,y2 onward as x1,y1 to x2,y2 is required to establish orientation.
Lazarus
@Lazarus: You're right; you should look at the difference between the angles.
SLaks
A: 

If you know the angle from point 2 to 1, and point 2 to 3, it's just a matter of angle_to_3 - angle_to_1, (or angle to next minus angle to previous) which you know how to calculate with atan2, or am I mistaken? Left /right / straight is just rounding the result. If you want to do it the hard way you can rotate your points so the angle from 2 to 1 is 0, but that seems unnecessarily convoluted.

Wrikken
A: 

Given your example of driving directions, the concept of left/right/straight only make sense in relation to the current direction of travel. This is why SatNav units start with the first turn or "Please proceed to the planned route" when you are off it's map rather than an immediate turn left/right/etc...

If you know the angle of x1,y1 to x2,y2 then you can give an indication of the relative direction for the next point using the angle x2,y2 to x3,y3. If the next angle is greater then it'll probably be a left turn, less is a right turn and within a certain margin around the first angle it'll be straight on.

Lazarus