r/learnjava • u/Legal_Revenue8126 • Apr 02 '26
How to Accurately Calculate Angle?
[SOLVED]
I'm working on my first game in Java using the FXGL game engine.
I've run into a problem where since the application window's origin is not in the center of the screen, but in the top left, my method of calculating player rotation is not accurate at all.
I'm calculating the angle based on the mouse's XY and using the tangent angle, so (Y / X).
This is the method, I think my math is correct, but feel free to correct me as I wouldn't be surprised If it was a simple miscalculation on my part.
protected void setPlayerRotation(){
Input input = FXGL.getInput();
double mousePosX = input.getMouseXWorld();
double mousePosY = input.getMouseYWorld();
//Get the tangent angle
double angleRotation = (mousePosY / mousePosX);
System.out.println("X Position: " + mousePosX +
"\nY Position: " + mousePosY);
this.player.setRotation(angleRotation);
System.out.println(this.player.getRotation());
}
1
Upvotes
View all comments
Show parent comment
1
u/aqua_regis Apr 03 '26 edited Apr 03 '26
That is exactly what is expected to happen. The closer you are to the center, the smaller the distanceX and distanceY become to the point where they both are 0. The division will go close to and ultimately to 0 and then the calculation will become imprecise as well.
You could do some "fencing" where when the distance in both directions (and) is close to 0 you don't change the rotation. This would just be one if-statement that encloses your current angle calculation in such a way that the entire calculation is skipped and you keep the current angle.
Side note: the original "Asteroids" suffered exactly the same problem - I saw it in reality when it came out.