Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angle between 2 points with atan2

Tags:

java

atan2

I was reading this post about getting an angle between 2 points and was wondering. I thought atan2 is defined for atan2(y,x) here it is atan2(deltaX, deltaY), why is x first now?

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.x - x, target.y - y));

    if (angle < 0) {
        angle += 360;
    }

    return angle;
}
like image 764
vuvu Avatar asked May 18 '26 02:05

vuvu


2 Answers

Math.java it define as

 public static double atan2(double y, double x) {
    return StrictMath.atan2(y, x); // default impl. delegates to StrictMath
  }

and this will return the counter-clock wise angle with respect to X- axis.

If you interchange those two you will get the clock wise angle with respect to X- axis.

In Cartesian coordinate system we consider counter-clock wise angle with respect to X-axis. That is why Math.java use this as above.

like image 104
Ruchira Gayan Ranaweera Avatar answered May 19 '26 16:05

Ruchira Gayan Ranaweera


Swapping the order of the arguments means that instead of the (counter-clockwise) angle with the X-axis you get the (clockwise) angle with the Y-axis. It's not wrong, just unusual.

like image 36
Joni Avatar answered May 19 '26 15:05

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!