I need to calculate the angle in degrees between two points for my own Point class, Point a shall be the center point.
Method:
public float getAngle(Point target) { return (float) Math.toDegrees(Math.atan2(target.x - x, target.y - y)); }
Test 1: // returns 45
Point a = new Point(0, 0); System.out.println(a.getAngle(new Point(1, 1)));
Test 2: // returns -90, expected: 270
Point a = new Point(0, 0); System.out.println(a.getAngle(new Point(-1, 0)));
How can i convert the returned result into a number between 0 and 359?
Java toDegrees() method with ExampleMath. toDegrees() is used to convert an angle measured in radians to an approximately equivalent angle measured in degrees. Note: The conversion from radians to degrees is generally inexact; users should not expect cos(toRadians(90.0)) to exactly equal 0.0.
you could add the following:
public float getAngle(Point target) { float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x)); if(angle < 0){ angle += 360; } return angle; }
by the way, why do you want to not use a double here?
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