Search code examples
javamathgame-enginegame-physicsangle

Is angle to the left or right of second angle


I need to know if another angle is on the right or on the left of the source angle.

I tried to subtract the angles and get the absolute value of them, but the range is from -180 to 180 meaning that when I go to 180 and go over to -180 it will give me the opposite answer.

If you are wondering what this is for, is for a Java Game I am developing where there is a tank turret controlled by the mouse.


Solution

  • It depends on whether your angles specify a rotation in the clockwise or anti-clockwise direction. If you are looking in the direction of the tank turret, then an object is on the right if you need to rotate the turret clockwise to point at it as quickly as possible, and on the left if you need to rotate anti-clockwise.

    Obviously, you can rotate in the opposite direction to go "the long way around": if an object is 10 degrees to the right then you can either rotate 10 degrees clockwise or 350 degrees anti-clockwise to point at it. But let's consider only the short way around, assuming that angles are specified in a clockwise direction:

    // returns 1 if otherAngle is to the right of sourceAngle,
    //         0 if the angles are identical
    //         -1 if otherAngle is to the left of sourceAngle
    int compareAngles(float sourceAngle, float otherAngle)
    {
        // sourceAngle and otherAngle should be in the range -180 to 180
        float difference = otherAngle - sourceAngle;
    
        if(difference < -180.0f)
            difference += 360.0f;
        if(difference > 180.0f)
            difference -= 360.0f;
    
        if(difference > 0.0f)
            return 1;
        if(difference < 0.0f)
            return -1;
    
        return 0;
    }
    

    After subtracting the angles, the result can be in the range of -360 (-180 minus 180) to 360 (180 minus -180). You can bring them into the range of -180 to 180 by adding or subtracting 360 degrees, then compare to zero and return the result.

    Angles with an absolute value between 180 and 360 correspond to the "long way around" rotations, and adding or subtracting 360 converts them to the "short way around". For example -350 degrees clockwise the long way around (i.e. 350 degrees anti-clockwise) plus 360 equates to 10 degrees clockwise the short way around.

    If the angles are specified in an anti-clockwise direction, then the meaning of the return value is reversed (1 means left, -1 means right)