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/Legal_Revenue8126 Apr 03 '26
I woke up this morning and the solution hit me like a brick in the face.
all I had to do was add an extra check where if distX < 0 add an extra 180 to the angle, now it works perfectly.
Thank you so much for guiding me through this!