Search code examples
javamathlibgdx

Angle between two vectors/points


I have the following function

public float getAngle(Point p2) {

    return (float) (MathUtils.radiansToDegrees * (Math.atan2(p2.y - y, p2.x - x)));
}

The problem I have is that the angles returned look like -20 (I would expect 20) or 50 when I would expect 310. What is the right way to get the values in the "normal" range from 0 to 359 anticlockwise?


Solution

  • double deg = MathUtils.radiansToDegrees * Math.atan2(p2.y - y, p2.x - x);
    deg = deg > 0 ? 360 - deg : 0 - deg;
    return (float) deg;
    

    This will give you the degree from [0, 360) in an anticlockwise manner.

    Note: using 0 - deg instead of -deg is to make sure 0.0 will not be converted to -0.0.