Making things random in a game can be very important. There many different ways to use this important method that I will be going over today.
The random method can be used for a variety of things. It is called when you want to generate a random number. This randomly generated number can be used to determine where a power-up will appear on a race track or how much damage an attack will do. Here is an example of it’s usage.
damage = Math.round(Math.random()*10);
Now I’m going to explain what the piece of code does. Okay, lets start by explaining that Math.random generates a number between 0 and 1. This number is then multiplied by the number 10. Then, that new number is rounded to the nearest whole number by the statement Math.round. All of this is then set equal to damage. So after this code is run, it will come out with a whole number between 0 and 10.
Another way to round is by using floor. This will chop off the decimal places. So if the number is 7.88, it will become just 7.