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...
Formula for angle between two Vectors The cosine of the angle between two vectors is equal to the sum of the product of the individual constituents of the two vectors, divided by the product of the magnitude of the two vectors. =| A | | B | cosθ.
To calculate the angle between two vectors in a 3D space: Find the dot product of the vectors. Divide the dot product by the magnitude of the first vector. Divide the resultant by the magnitude of the second vector.
Formulas for Angle Between Two Lines The angle between two lines, of which one of the line is y = mx + c and the other line is the x-axis, is θ = Tan-1m. The angle between two lines that are parallel to each other and having equal slopes (m1=m2 m 1 = m 2 ) is 0º.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With