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 anyone improve on the code below making it a bit more robust?
public void Rotate(int degrees) { this.orientation += degrees; if (this.orientation < 0) { while (this.orientation < 0) { this.orientation += 360; } } else if (this.orientation >= 360) { while (this.orientation >= 360) { this.orientation -= 360; } } }
A normalized angle maps the full range of angles (360 degrees) to the range zero to one. The following table shows the relationship between normalized angles and degrees: Normalized. Degrees. 0.
Positive and Negative Angles The measure of an angle describes the magnitude and direction of the rotation of the ray from its initial position to its terminal position. If the rotation is counterclockwise, the angle has a positive measure. If the rotation is clockwise, the angle has a negative measure.
What is Wrap Angle? Wrap Angle is a measurement in degrees of the diameter of a sensor roller that the tensioned material contacts. Most tension sensing rollers have a minimum and maximum wrap angle they are compatible with.
Use modulo arithmetic:
this.orientation += degrees; this.orientation = this.orientation % 360; if (this.orientation < 0) { this.orientation += 360; }
This is one that normalizes to any range. Useful for normalizing between [-180,180], [0,180] or [0,360].
( it's in C++ though )
// Normalizes any number to an arbitrary range // by assuming the range wraps around when going below min or above max double normalize( const double value, const double start, const double end ) { const double width = end - start ; // const double offsetValue = value - start ; // value relative to 0 return ( offsetValue - ( floor( offsetValue / width ) * width ) ) + start ; // + start to reset back to start of original range }
For ints
// Normalizes any number to an arbitrary range // by assuming the range wraps around when going below min or above max int normalize( const int value, const int start, const int end ) { const int width = end - start ; // const int offsetValue = value - start ; // value relative to 0 return ( offsetValue - ( ( offsetValue / width ) * width ) ) + start ; // + start to reset back to start of original range }
So basically the same but without the floor. The version I personally use is a generic one that works for all numeric types and it also uses a redefined floor that does nothing in case of integral types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With