Search code examples
javaif-statementcompassdegrees

Compass moving between 360 and 0 and checking if there is a negative change


I have a compass, that returns degrees between 0-360 and a starting position (degrees) of the initial value of the compass, along with a threshold.

degrees = 0-360
initialDegrees = null
threshold = 20

I have this check:

if(degrees > initialDegrees+threshold || initialDegrees == null) { // this is to start the checking
    foo(); 
    initialDegrees = degrees
}

for checking if the degrees have changed positively beyond the threshold (i.e. me moving the compass to the right)

However how do i check if it has been moved in the opposite direction (changed negatively beyond the threshold, i.e. me moving the compass to the left).

if(degrees > initialDegrees-thredshold) // this is always true, and doesn't do what i want

Is there a way i can do this? Hopefully you understand what I'm trying to achieve.


Solution

  • What you need is the shortestAngle function. Some math libraries already have it, but you can write your own. Given 2 angles, you need to find the smallest angle (in absolute value), such that the first angle plus this result equals the second angle:

    public static float shortestAngle(float from, float to) {
        float difference = to - from; //step 1: do flat difference
        difference %= 360; //step 2: do module 360 to normalize to (-360, 360) range
        if(difference < 0) {
            difference += 360; //step3: normalize to [0, 360) range
        }
        if(difference > 180) {
            difference -= 360; //step 4: normalize to (-180, 180] range
        }
        return difference;
    }
    

    After that you just compare if the shortest angle is greater than threshold, or lower than negative threshold.