Java: Determine the angle between two points

OK, firstly, an apology, because I know that this question was asked earlier than once. However, even after considering other questions and answers, I could not get this to work for my situation. The following is an example: Fig. 1

All I'm just trying to work out is the angle between P1 and P2, assuming 0 degrees as shown above so that I can direct the arrow between the two in the right direction. So I am doing something like this ...

Point p1 = new Point(200,300); Point p2 = new Point(300,200); double difX = p2.x - p1.x; double difY = p2.y - p1.y; double rotAng = Math.toDegrees(Math.atan2(difY,difX)); 

What happens: -45, where should there be 45? However, this is not just a case, I do not think that it returns a negative result, for example, if I changed P1 to 300 300 (below P2), then the angle should be 0, but it returns as -90.

So I'm just wondering if anyone can point out what I'm doing wrong to figure this out, or is it possible to do so?

+5
source share
3 answers

atan2(Y,X) calculates in the standard Cartesian coordinate system with a positive counterclockwise orientation the angle of the point (X,Y) against the ray through (1,0) . This means that X is the coordinate along the zero-angle ray, in your situation X=-difY , and Y is the coordinate in the direction of (small) positive angles, which gives, with your preference, the angle shown up to 45 Β°, Y=difX . Thus,

 double rotAng = Math.toDegrees(Math.atan2(difX,-difY)); 
+3
source

You are misleading the coordinate system used in geometry compared to that used on a computer screen. In geometry, you are regular, that 0,0 is a point in the lower left corner. However, 0.0 on the left screen is the top corner.

Now rotate the image in accordance with the coordinates of the screen and make sure that the angle is calculated correctly.

So, in the general case, you can choose one of the following solutions: 1. Count the coordinates of your points on the screen coordinates and vice versa. 2. If your problem is only in the corners, you can add Ο€ / 2 (90 degrees) to your result.

+3
source

With your line double difX = p2.x - p1.x; double difY = p2.y - p1.y; double difX = p2.x - p1.x; double difY = p2.y - p1.y; you calculate your angle from p2 to 0, so -45 is the correct answer. Try changing p1 to p2.

Also, if P1 is changed to 300 300, then you have an angle from 0 (from 0 to P1 and P1 to P2). The angle is really 90 or -90 if you see from P2 to 0 or from 0 to P2.

+1
source

Source: https://habr.com/ru/post/1216102/


All Articles