Search code examples
javaatan2

Angle between 2 points with 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;
}

Solution

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