1

So I want to get the degrees between 2 points, But when I want it to return 180, it returns 0... 0, 90 and 270 does work, but when its 180 it returns 0.. This is my code:

Location loc1 = new Location(Bukkit.getWorld("world"), 1, 0, 0);
Location loc2 = new Location(Bukkit.getWorld("world"), -1, 0, 0);

float pitch = Utils.yawpitch(loc1, loc2).getPitch();


public static Location yawpitch(Location loc, Location toloc) {

    loc = loc.clone();

    double x = toloc.getX() - loc.getX();
    double y = toloc.getY() - loc.getY();
    double z = toloc.getZ() - loc.getZ();

    double dxz = Math.sqrt(Math.pow(x, 2) + Math.pow(z, 2));
    loc.setPitch((float) -Math.atan(y / dxz));
    loc.setPitch(loc.getPitch() * 180f / (float) Math.PI);

return loc;

}

So I have my first point on the left and my second point on the right, so it should be 180, but this will return "0".

1 Answers1

2

It seems like what you want is to use Math.atan2 rather than Math.atan. Math.atan returns a value in the range of -π/2 to π/2 (i.e. -90° to 90°). This is because it would need the signs of both y and x to compute the correct quadrant out of 4, which is also why atan2 takes y and x as separate arguments.

(In other words, given some y and x, -y/x == y/-x. atan2 takes them separately so it can disambiguate cases like that.)

Also see What is the difference between atan and atan2 in C++? for more information. (The principles there apply to Java as well.)

As a side note, the trigonometric methods in Math generally operate in radians. If you're using degrees, you need to do a conversion.

Radiodef
  • 37,180
  • 14
  • 90
  • 125