Code Bits: Random
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.

September 27th, 2008 at 9:47 pm
[...] Free games by Director [...]
September 28th, 2008 at 8:38 pm
Not to sound picky, but 10 isn’t a variable in your example it’s a constant. You should probably just drop the word variable.
Also a useful variation of this formula is being able to generate a random number within a certain range.
lowNumber + Math.random() * (highNumber - lowNumber);
September 29th, 2008 at 1:55 am
Thanks for pointing that out. Originally I was using the variable strength there, but I thought it might be too confusing if I added in too many variables for a simple tutorial like this. So I ended up changing it to 10, and must have forgotten to remove the word variable.
And I never thought of doing it that way. I usually would just multiply by the difference between the two numbers I want to get, then add the lowNumber.
September 30th, 2008 at 7:49 pm
Isn’t that what my method is doing?
I have that particular method inside my own static Math class, aptly named Math2. So whenever I need a random number, say between 5 and 20 I call it like so: var myRandomNumber:Number = Math2.random(5,20);
Obviously you’d need to import Math2 before using it.