Mathematical calculation to get the angle between two points?

Possible duplicate:
How to calculate the angle between two points relative to the horizontal axis?

I have been looking for this for ages and it just annoys me very much, so I decided to just ask ...

If I have two points (namely x1, y1 and x2, y2), I would like to calculate the angle between these two points, assuming that for y1 == y2 and x1> x2, the angle is 180 degrees ..

I have the code below that I was working on (using knowledge from high school), and I just can’t imagine 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 so upset ...

+8
math c # distance angle
source share
1 answer

From what I have compiled, you want to keep the following:

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

Clockwise horizontal line rotation

You said you want to increase the angle clockwise.

Turn this line P1 -------- P2 so that P1 above P2 , the angle should be 90 Β°.

If, however, we turn in the opposite direction, P1 will be below P2 , and the angle will be -90 Β° or 270 Β°.

Work with atan2

The basis . Considering P1 as the origin and measuring the angle P2 relative to the origin, then P1 -------- P2 will correctly give 0 .

 float xDiff = x2 - x1; float yDiff = y2 - y1; return Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI; 

However, atan2 , the angle increases in the direction of CCW. Rotating in the CCW direction around the origin, y passes the following values:

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

This means that we can simply invert the y sign to flip the direction. But since C # coordinates increase from top to bottom, the sign is already canceled when calculating yDiff .

+15
source share

All Articles