Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Calculating the angle between two points in degrees

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?

like image 347
Aich Avatar asked Apr 02 '12 02:04

Aich


People also ask

How do you calculate degrees in Java?

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.


1 Answers

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?

like image 108
John Ericksen Avatar answered Sep 21 '22 01:09

John Ericksen