OK firstly apologies as I know this kind of question has been asked before more than once. However even after looking at the other questions and answers I have been unable to get this to work for my situation. See below for an example:
All I am simply trying to is work out the angle between P1 and P2 assuming that 0 degrees is as shown above so that I can point an arrow between the 2 in the correct direction. So I do 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));
Which comes out as: -45, where it should be 45? However it is not simply a case I don't think of it returning a negative result, as for example if I changed P1 to 300,300 (below P2) then the angle should be 0, but is returned as -90.
So I am just wondering if anyone can point out what I am doing wrong to calculate this, or is it even possible to do it this way?
double angle = atan2(y2 - y1, x2 - x1) * 180 / PI;".
atan2(Y,X)
computes in the standard Cartesian coordinate system with anti-clockwise positive orientation the angle of the point (X,Y)
against the ray through (1,0)
. Which 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 for the depicted angle to be 45°, Y=difX
. Thus
double rotAng = Math.toDegrees(Math.atan2(difX,-difY));
You are confusing with the coordinates system used in geometry vs. one used on computer screen. In geometry you are regular that 0,0 is a point in the left bottom corner. However 0,0 on screen is left - upper corner.
Now, rotate your picture according coordinates of screen and see that the angle is calculated correctly.
So, in general case you can choose one of the following solutions: 1. recalculate corrdinates of your points to screen coordinats and back. 2. if your problem is in angles only you can add π/2 (90 degrees) to your result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With