AS3 Tutorial – Math.random()
i haven’t written many Flash tutorials because i feel like a bit of a poser. i see the brilliant codeheads posting these tutes to make Flash do incredible things and i think “man – that’s leagues ahead of where i’m at.” But i forget that with eight years’ experience using Actionscript, i do actually know a thing or two that will help someone new to Flash/Actionscript.
This article is from an email i sent to a Humber College student explaining how to pull a random number in Flash, how to make it an integer, and how to get a random number within a range.
The student, Michael, was creating a game with an asteroid belt. He wanted to randomly distribute the asteroids along the y axis, and to give them a random speed value within a range. The range would increase with each new level.
~~ BEGIN TRANSMISSION ~~
Hi Michael.
Whenever you want x amount of something, that’s obviously your cue to create a variable. So since you need x amount of asteroids, let’s make a totalAsteroids variable:
var totalAsteroids:uint = 5; // you can tweak this value up or down, of course
The other two things you’re looking at are random numbers within ranges. You need a random number within a range to distribute the asteroids along the y axis. You need a random number within a range to determine the speed of the asteroids, which goes up (i assume?) each level.
So! Here’s the basic random code:
var someNumber:Number = Math.random();
That’ll get you a decimal number betwen 0 and 1. Try running this code a few times in Flash to prove it:
var someNum:Number = Math.random(); trace(someNum);
You just multiply that number if you need a bigger range. Look at this:
var someNum:Number = Math.random()*5;
That will give you a decimal number between 0 and 5, because everything has been multiplied by 5.
Decimal numbers might not serve your purposes well. Here are a few ways to clean up your someNum result:
var someNum:Number = Math.floor(Math.random()*5); // gives you 0, 1, 2, 3, or 4 by "flattening" the decimal number var someNum:Number = Math.ceil(Math.random()*5); // gives you 1, 2, 3, 4, or 5 by raising the decimal number var someNum:Number = Math.round(Math.random()*5); // gives you 0, 1, 2, 3, 4, or 5 by rounding the decimal number up or down
See? You just wrap Math.roundingMethod() around your Math.random() method. You stick your Math.random() statement inside the Math.roundingMethod() brackets.
So far so good. Now what if you need a random number within a range? Say, any number between 5 and 20?
Well, 20 minus 5 is 15. That’s your range. You need a random number out of 15.
Then just add the lower limit (5) to bump the number up. Does that make sense?
var someNum:Number = Math.ceil(Math.random()*15); // gives you 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, or 15 var someNum:Number = Math.ceil(Math.random()*15) + 5; // gives you 5, 6, 7, 8, ,9 ,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, or 20
So really, we could knock all these numbers out and just use variables.
var minLimit:uint = 5; var maxLimit:uint = 20; /* These two variables change depending on the level of the game. To be more specific, they'll probably be called minSpeed and maxSpeed.*/ var range:uint = maxLimit - minLimit; var someNum:Number = Math.ceil(Math.random()*range) + minLimit;
This works for your asteroid speed. It also works for asteroid placement. Do you see how? You’re just telling Flash the minimum limit for asteroid placement (somewhere near the top of the gameplay field) and the maxiumum limit (near the bottom of the screen). Then you pull a random number within that range and bump the number up by adding the minLimit value.
To create your asteroids field, loop through your totalAsteroids value, and for each asteroid you add to the screen from the library, get a random number within range and set the asteroid’s y position to that result.
Obviously what’s missing here is the game’s update and draw loops which will position the asteroids and position their graphics. i’ll save that for another post. Addendum: Props to SmilyOrg from #actionscript on EFNet for the random direction code. i use it all the time, and i always forget how it goes. Popularity: 100% [?]
for(var i:uint = 0; i<totalAsteroids; i++)
{
var theAsteroid:Asteroid = new Asteroid();
// create a new instance of your Asteroid class (not shown)
var theClip:MovieClip = theAsteroid.clip = new AsteroidClip();
// attach a MovieClip from the library
theAsteroid.clip.y =
Math.ceil(Math.random()*screenRange) + minYLimit;
// Pull a random screen position
theAsteroid.speed =
Math.ceil(Math.random()*speedRange) + minSpeed;
// Pull a random speed
theAsteroid.dir = Math.round(Math.random())*2-1;
// Randomly grab 1 or -1 for the direction.
// During the game's update loop, multiply the speed
// by the direction to make the asteroid move left to right,
// or right to left
theAsteroid.dir == 1 ?
theAsteroid.clip.x = 0 : theAsteroid.clip.x = maxXLimit;
// Put the asteroid at the right or left side of the screen,
// depending on which direction it'll be travelling
addChild(theAsteroid.clip);
// Put that puppy on the stage!
}


(11 votes, average: 4.91 out of 5)
Email This Post
good tutorial. I love your site, couldn’t bookmark it quick enough. The animation in your navigation and all the hand drawn elements are amazing.
Thanks for the pick-me-up! You made my day.
i haven’t penned a Flash tutorial in a while. Part of me worries that i’ll write something that too many people understand, and it’ll have a big “duh” factor to it. But i can’t discount the fact that different people come in with different levels of experience.
If there’s a tutorial you’d like to see here, or an AS3 issue you’d like cleared up, let me know!
Hi, nice tutorial there, but I want to say something about your rounding:
random() * 5 gives you a float value between 0 and 5, but when you make it an int by ROUNDing it, you must be aware that 0 and 5 are more unlikely to occure than the other values! because only values from 0..0.49999~ will round to 0 and values 4.5 to 5 will round to 5.
but e.g. values 0.5..1.4999999~ will all be rounded to 1, so the probability is twice as large.
so one should always go with ceil.
I’d suggest to write a little helping function to make your code more readable and usable:
function randomInRange(from:int, to:int):int {
return Math.ceil(Math.random() * (to – from + 1)) + from;
}
// haven’t checked the code, but I hope you just get the picture (so noone should just copy this code without testing ;) – maybe there will be some index-offsets ;) )
Thanks, Dennis. Math and i haven’t really spoken to each other since high school. Our relationship has been a little strained.
Love the Tutorial! You said if we had any request just ask, well……… Sorry if this seems a little simple but have been looking for a basic tutorial for age on this to get a firm understanding. Classes for beginners! making and using basics. I see you have related tuts to this but would love some more info.
Ryan – thanks for your request! i’ll get right on it.
- Also Ryan
Good job man. Helped e more than most tuts! Keep it up. God bless
Thank you this was just what i was searching for, Thanks to you and google , I found it :)
one other note: if you add 5 to the range or 1-20 you get 6 to 21
var someNum:Number = Math.ceil(Math.random()*15);
// gives you 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, or 15
var someNum:Number = Math.ceil(Math.random()*15) + 5;
// gives you 5, 6, 7, 8, ,9 ,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, or 20
add 4 instead :)
Loves Math ^_^
LOL my mistake I ment when you add 5 to a set of 1 to 15** you get 6 to 20** ><
is that right? adding 0 gives u 1 to 15… adding 4 would get you 5 to 19 , adding 5 gives you 6** to 20..
Goes back to study more flash coding :) Peace…
good tutorial…..Thanks
Thanks for this.
Fast and made sense.
Matt – thanks! Would you believe that this article remains the most high-traffic page on my site?
[...] it was going little too well. This required some research and the best tutorial I could find is here at the awesome site untoldentertainment.com. Make sure you read the comments as they discuss the [...]
Hi!
How to get random letter? for example, you can get random color.
Math.random()*0xffffff
conscience: You can either build your own discreet array, and choose a random index in that array:
aLetters = ["A", "B", "C"];
or you could pull a random number using the keycodes or ascii codes for the letters. Use this table for reference:
http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001136.html
- Ryan
Thanks.
I made It with String.
var a : String = “qweertyiop[asdjhfmvxcjhgf”;
and take random letter from It. maybe it is faster?
conscience – i could be wrong, but i remember hearing or reading somewhere that substring operations are slow. What you’ve done here takes less typing than the array method, but it may not execute as quickly. If you’re not too concerned about speed, then i say “go with whatever works.”
Ryan,
Thanks a bunch for the tut, working knowledge of random numbers is definitely something a budding programmer needs to know.
In reference to as3 beginner’s post, he or she is correct to say that:
var minLimit:Number = 5;
var maxLimit:Number = 20;
var range:Number = maxLimit – minLimit;
var someNum:Number = Math.ceil(Math.random() * range) + minLimit;
…would return 6-20, not 5-20. Reason being the lowest possible return value of “Math.ceil(Math.random() * range)” is 1, and 1+ 5 = 6.
Changing the minimum to 4, however, will yield 5-19, leaving us one short of the maximum of 20. If the range is increased to 16, we finally get our target return of 5-20. So, to get the true minimum and maximum of the variables we have declared, we modify our code to look like this:
var minLimit:Number = 5;
var maxLimit:Number = 20;
var range:Number = maxLimit – minLimit + 1;
var someNum:Number = Math.ceil(Math.random() * range) + minLimit – 1;
trace(someNum);
Copy/pasting this code and running it in Flash will reveal that the numbers you get are, indeed, from 5 to 20. Hope this helps. Though, it wouldn’t help nearly as much as this tutorial. I’m very grateful for the writeup — keep up the good work.
–Cody
Cody – thanks for the additional code! It really surprises me that this post remains the most popular one on the site for a number of years.