Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math Calculation to retrieve angle between two points? [duplicate]

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...

like image 836
Luke Joshua Park Avatar asked Oct 15 '12 08:10

Luke Joshua Park


People also ask

What is the formula to find the angle between two vectors?

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θ.

How do you find the angle between 2 3D vectors?

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.

What is the formula for finding the angle between two lines on a Cartesian plane?

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º.


1 Answers

From what I've gathered, you want the following to hold:

  • Horizontal line: P1 -------- P2 => 0°
  • Horizontal line: P2 -------- P1 => 180°

Rotating the horizontal line clockwise

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°.

Working with 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:

  • y = 0
  • y > 0
  • y = 0
  • y < 0
  • y = 0

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.

like image 99
phant0m Avatar answered Sep 18 '22 13:09

phant0m