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