0

I need to get angle between two points on the flat(x,y), for example I have points A and B, point A have directions(90), how could I count angle between points A and B from A directions in Java?

Here's an image for example:

enter image description here

Léo Lam
  • 3,870
  • 4
  • 34
  • 44
Martin Gut
  • 31
  • 1
  • 6

1 Answers1

4
Math.toDegrees(Math.atan(Math.abs(pointBY - pointAY), Math.abs(pointBX - pointAX)));

This calls the inverse tangent function to find an angle based on the lengths of the opposite and adjacent sides of a right angled triangle. However, you should add this if statement:

if(!(pointAX == pointBX || pointAY == pointBY))
{
angle = Math.toDegrees(Math.atan(Math.abs(pointBY - pointAY), Math.abs(pointBX - pointAX)));
}

Otherwise you can cause an exception because the tan function breaks down if the angle is 90 or 0 degrees.

pointAX and pointBX are the X coordinates of the points, while pointAY and pointBY are the Y coordinates of the points.

This function finds the absolute value of the difference between the coordinates (so the length of the opposite and adjacent sides of the right-angled triangle formed from the two points) and then performs the inverse tan function on them, finding the angle.

imulsion
  • 8,820
  • 20
  • 54
  • 84
  • Thank you, I understood, how to get angle between A and B points, but I don't understand how get angle between AB angle and A direction, here's small example what I need there is 3 points A1,A2 and B, points A has direction, image: http://cs614922.vk.me/v614922073/13f87/a3d26coYe-4.jpg – Martin Gut Jul 28 '14 at 16:21
  • Please not that the code above is incorrect. java.lang.Math.atan does not take in two variables. The author meant to use atan2 instead. – EndOfAll Mar 05 '20 at 18:22