In RSL and most other programming languages, the modulus operator is represented by the % symbol. The modulus operator finds the remainder after dividing one number by another. The modulus operator is similar to whole number division used by children that have not learned fractions. For example, 10 / 3 is 3 remainder 1. The modulus operator gives you the remainder value of 1. In the code below, a value of 1 is added to the print log. This is because 3 divides evenly into 10 three times, leaving a remainder of 1.
In Robot Battle, the modulus operator is commonly used with rotational angles. Since rotational angles repeat every 360 degrees, the modulus operator is used to trim angles to their smallest equivalent between 0 and 359. In the code below, what are the possible values of angle? Since _bodyaim can range from 0 to 359, the possible values of angle are from 180 to 539.
Since angles are usually needed as values between 0 and 359, the modulus operator is used to trim angles by taking out multiples of 360 and leaving the remainder. The following modified code produces a value between 0 and 359.
If _bodyaim had a value of 310, the first part of the calculation above would produce 490 (310 + 180). The modulus operator then finds the remainder of dividing 490 by 360. This produces a final angle of 130. 130 is equivalent to an angle of 490, but is in the desired range of 0 to 359.
The thought process for using the modulus operator often goes like this:
See Also