Possible Duplicate:
How to calculate the angle between two points relative to the horizontal axis?
I’ve been looking for this for ages and it’s just really annoying me so I’ve decided to just ask…
Provided I have two points (namely x1, y1, and x2, y2), I would like to calculate the angle between these two points, presuming that when y1 == y2 and x1 > x2 the angle is 180 degrees…
I have the below code that I have been working with (using knowledge from high school) and I just can’t seem to produce the desired result.
float xDiff = x1 - x2;
float yDiff = y1 - y2;
return (float)Math.Atan2(yDiff, xDiff) * (float)(180 / Math.PI);
Thanks in advance, I’m getting so frustrated…
From what I’ve gathered, you want the following to hold:
P1 -------- P2=> 0°P2 -------- P1=> 180°Rotating the horizontal line clockwise
You said, you want the angle to increase in clockwise direction.
Rotating this line
P1 -------- P2such thatP1is aboveP2, the angle must thus be 90°.If, however, we rotated in the opposite direction,
P1would be belowP2and the angle is -90° or 270°.Working with
atan2Basis: Considering
P1to be the origin and measuring the angle ofP2relative to the origin, thenP1 -------- P2will correctly yield0.However,
atan2let’s the angle increase in CCW direction.Rotating in CCW direction around the origin,
ygoes through the following values:This means, that we can simply invert the sign of
yto flip the direction. But because C#’s coordinates increase from top to bottom, the sign is already reversed when computingyDiff.