Math requires a number between -180 and 180

I have a math problem.

In minecraft, yaw can be between -180 and 180, now I need to add 90 to the player's yaw. but if the yaw is 150 + 90 = 240, which is greater than 180, how can I add 90, but if it moves 180 samples further by -180.

Examples:

-150 + 90 = -60, No problem
0 + 90 = 90, No problem
150 + 90 = 240, Problem it needs to be -120

      

-five


source to share


3 answers


You can solve it like this:

private static final int MIN = -180;
private static final int MAX = 180;

public static void main(String[] args) {
    System.out.println(keepInRange(-150 + 90));
    System.out.println(keepInRange(0 + 90));
    System.out.println(keepInRange(150 + 90));
    System.out.println(keepInRange(-150 - 90));
}

private static int keepInRange(final int value) {
    if (value < MIN) {
        /*
         * subtract the negative number "MIN" from "value" and
         * add the negative result to "MAX" (which is like subtracting the absolute value
         * of "value" from "MAX)
         */
        return MAX + (value - MIN);
    }
    if (value > MAX) {
        /*
         * subtract the number "MAX" from "value" and to get exceeding number
         * add it to "MIN"
         */
        return MIN + (value - MAX);
    }
    return value;
}

      

Output:



-60
90
-120
120

As per your explanation, the last values ​​should be -120 and 120, not -60 and 60 as you said in your example. The over-sum must be added to the "other" boundary, not from 0. 150 + 90

equals 240, so it exceeds the MAX pegged to 60. This must then be added to the MIN boundary. The result is -120.

If this is not correct please update your question.

0


source


This is a classic example of modular arithmetic. You can use the remainder operator %

.

    int current = 150;
    int input = 90;
    int newCurrent = ((180 + current + input) % 360) - 180;

    System.out.println("NEW: " + newCurrent);

      



Output:

 NEW: -120

      

+1


source


You can use the modulo operator on positive numbers, it looks like division, but gives you the rest instead of the quotient:

10/6 = 1,66666...
10%6 = 4

For you: ( 150 + 90 ) % 180 = 60

      

0


source







All Articles