Normalise orientation between 0 and 360

前端 未结 9 1605
不知归路
不知归路 2021-01-30 10:58

I\'m working on a simple rotate routine which normalizes an objects rotation between 0 and 360 degrees. My C# code seems to be working but I\'m not entirely happy with it. Can a

9条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 11:36

    This can be simplified to the following.

    public void Rotate (int degrees) {
        this.orientation = (this.orientation + degrees) % 360;
        if (this.orientation < 0) this.orientation += 360;
    }
    

    C# follows the same rules as C and C++ and i % 360 will give you a value between -359 and 359 for any integer, then the second line is to ensure it's in the range 0 through 359 inclusive.

    If you wanted to be shifty, you could get it down to one line:

        this.orientation = (this.orientation + (degrees % 360) + 360) % 360;
    

    which would keep it positive under all conditions but that's a nasty hack for saving one line of code, so I wouldn't do it, but I will explain it.

    From degrees % 360 you will get a number between -359 and 359. Adding 360 will modify the range to between 1 and 719. If orientation is already positive, adding this will guarantee it still is, and the final % 360 will bring it back to the range 0 through 359.

    At a bare minimum, you could simplify your code since the ifs and whiles can be combined. For example, the result of the conditions in these two lines:

    if (this.orientation < 0)
    while (this.orientation < 0)
    

    is always the same, hence you don't need the surrounding if.

    So, to that end, you could do:

    public void Rotate (int degrees) {
        this.orientation += degrees;
        while (this.orientation <   0) this.orientation += 360;
        while (this.orientation > 359) this.orientation -= 360;
    }
    

    but I'd still go for the modulus version since it avoids loops. This will be important when a user enters 360,000,000,000 for the rotation (and they will do this, believe me) and then find they have to take an early lunch while your code grinds away :-)

提交回复
热议问题