In my top down shooter game, the player can face in any of the 8 compass directions using the keyboard.
Depending on the direction, the player will have a 90 degree field of view to turn based on the angle selected by the mouse position. Obviously the mouse can go anywhere so it has to be restricted within -45 and 45 of the angle faced.
The eight direction angles:
135 90 45
180 0
225 270 305
So if the player is facing to the left at 180, their range of view will be -45 and 45 of that ie 135 to 225. So it's simply mouseAngle - facingAngle
, which works fine, except if the player is facing around 0, 45 or 305 degrees where the mouse angle passes zero causing issues in calculation.
As it is I'm using this formula.
private void setAngleFOV() {
if (facing == 0 || facing == 360)
facing = mouseAngle < 360 && mouseAngle >= 180 ? 360 : 0;
angleFOV = mouseAngle - facing;
angleFOV = Math.max(Math.min(angleFOV, 45), -45);
}
It can either be 0 or 360 for either facing
or mouseAngle
, whichever works best but I haven't found an ideal solution. The above formula works for facing right at angle 0, but not with diagonal angles 45 and 305.
It could maybe work with lots of if
statements and such, but I feel there must be a better way?