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?
clampAbsoluteAngle(angle, 180, 45)
withangle
less than 135, I get the value 135 back. When I use anangle
between 135 and 225, I getangle
back unchanged. And when I use anangle
greater than 225, I get 225 as output. Is that not what you want? – DMGregory Jun 27 '20 at 15:14facing
can't be changed, I just add angleFOV to it where it is needed. – Hasen Jun 27 '20 at 15:16(float)
casts on the returns fordeltaAngle
andclampAbsoluteAngle
. – Hasen Jun 27 '20 at 15:23Mathf
type in Unity which returns floats natively. ;) Don't forget to search in future. You're not the first person to wrestle with angle wraparound issues, so there are a lot of existing answers about how to get the difference between two angles. – DMGregory Jun 27 '20 at 15:25