Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | SebSharper |
I am making a top down shooter game, and I wanted to check if the mouse position converted to angle is equal to some of the following angles: 0, 90, 180 and 360.
Of course, that this won’t work because it is very specific (the player would have to point to the angle directly, with a superhuman precision), so I thought about checking if the mouse position to angle is in a range, so that it would have some sort of tolerance.
This is my code:
const FLOAT_EPSILON = 0.000001
#45 of tolerance, this means that if the direct angle is 90, the corresponding range is (90 - 45): 45 (minimum value) and (90 + 45): 135 (maximum value)
if is_inside_range(angles, 45, 135): #90 direct angle
print("down")
elif is_inside_range(angles, 136, 225): #180 direct angle
print("left")
elif is_inside_range(angles, 226, 315): #270 direct angle
print("up")
elif is_inside_range(angles, 316, 360): or is_inside_range(0, 45) #360 direct angle
print("right")
func is_inside_range(val : float, min_val : float, max_val : float) -> bool:
return val >= (min_val - FLOAT_EPSILON) and val <= (max_val + FLOAT_EPSILON)
As you can see, this should work well, and it does, except for one little issue. If the angles variable is too close to the beggining/end of a range of values (for example, if it is 90.1), but not the exact value, it will print two states
How could I fix this error? Is there a better way to achieve this?