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°You said, you want the angle to increase in clockwise direction.
Rotating this line P1 -------- P2
such that P1
is above P2
, the angle must thus be 90°.
If, however, we rotated in the opposite direction, P1
would be below P2
and the angle is -90° or 270°.
atan2
Basis: Considering P1
to be the origin and measuring the angle of P2
relative to the origin, then P1 -------- P2
will correctly yield 0
.
float xDiff = x2 - x1;
float yDiff = y2 - y1;
return Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI;
However, atan2
let's the angle increase in CCW direction.
Rotating in CCW direction around the origin, y
goes through the following values:
This means, that we can simply invert the sign of y
to flip the direction. But because C#'s coordinates increase from top to bottom, the sign is already reversed when computing yDiff
.