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.


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();

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);
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.

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
   // Put that puppy on the stage!

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.

37 thoughts on “AS3 Tutorial – Math.random()

  1. Dave

    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.

  2. Ryan

    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!

  3. Dennis

    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 ;) )

    1. Ryan

      Thanks, Dennis. Math and i haven’t really spoken to each other since high school. Our relationship has been a little strained.

  4. Ryan

    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.

  5. as3 beginner

    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);

    add 4 instead :)

    Loves Math ^_^

  6. as3 beginner

    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…

  7. Pingback: Randomly placing a child on the stage |

    1. Ryan

      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.”

  8. Cody


    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;

    …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;

    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.


    1. Ryan

      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.

  9. Bergen

    Good work! And good point about Math.round for 0-0.499 being less likely than .5-1.499, Dennis. However, there is one thing all of you are missing.

    From the ActionScript Reference on Math:
    [static] Returns a pseudo-random number n, where 0 <= n < 1.

    So, we can return 0, but never 1

    You had said:
    var someNum:Number = Math.ceil(Math.random()*5);

    BUT, Math.ceil(Math.random()*5) will, a very very small percentage of the time, return 0… and THAT my friends, is where babies come from. I mean bugs.

  10. Freddy

    totalAsteroids is undefined, screenRange is undefined, speedRange is undefined. Your tutorial using Math.random was great but why are you illustrating with an example that is uncompleted ?
    I am going to start wondering if you really know how to build real programs Sir.:)

  11. Jeffrey

    I am trying something different. I have a number generate and it tells me the number in the output tab, however how do I call the number to my if else statement. I have a bit of the code here:

    function randRange(min:Number, max:Number):Number { 
        return randomNum; 
        var n:Number = randRange(1, 13) 
    if (n == 1) {
    	gotoAndPlay (50); 
    } else if (n == 2) {
    	gotoAndPlay (50); 
    } else if (n == 3) {
    	gotoAndPlay (85);
    1. Ryan Henson Creighton

      Jeffrey – just transplant your conditional snippet so that it’s inside the statement block of your loop.

      1. Jeffrey

        Can spell it out, I did flash in collage 7 years ago and was not good at it, so I am digging deep to get this far. So what would that look like.

        1. Ryan Henson Creighton

          Hmm … it troubles me that you spelled “college” incorrectly, and that you’re asking me to fix code that you copy-pasted without understanding it because you were too high seven years ago to pay attention in class.

          But since i strongly believe in wasting my time to help people who aren’t willing to put even a modicum of effort into their craft, here’s your code:

          var str1 : String = "f";
          var str2 : String = "uck o";
          var str3: String = "ff";
          for(var i:int =0; i<5000; i++)
              trace(str1 + str2 + str3 + " and die.");
          1. Jeffrey

            I tried this I can not get it to work, can please check and make sure that all the punctuation is correct. I was told that if you put an extra space in it may not work correctly.

          2. Ryan Henson Creighton

            Works for me. Just open a new Flash file, paste it into the first frame’s Actions, and build/run the movie.

  12. Pete

    I just found this blog a few days ago, and several times I’ve idly returned to read bookmarks, but this is the first time I’ve ventured into the comments for any of the posts.

    I find myself wishing for more posts than are currently available now. =p

    (like seriously, add interfaces to your oop section and the A* series needs a little more handholding!)

    1. Ryan Henson Creighton

      Thanks, Pete! It’s funny – the A* article was actually written by one of our programmers (who’s since left us) Phil Chertok. A few months after Phil departed, i actually sat down to write some A* pathfinding and i thought “oh – how convenient. i’ll just use Phil’s article.” i actually had the same problem … not simple enough.

      i did find a MUCH simpler A* primer, but it was so simple that it went on for pages and pages explaining how the algorithm works. It was a great instructional tool, but it was outside of the scope of what Phil was writing here … after all, he had a game to program for me!

      Anyway, these are the lessons i followed. i can’t recommend them enough:

      (oh – and thanks for the article requests! You’re the first person to take me up on that)

  13. Hoang

    Again, very clear tutorial.Love it :D
    By the way, I wonder how Flash and other programming languages actually create a random number?
    I’ve been told that it’s somewhere in computer clock (or something), but I can’t either see the point or make sure if I can trust its “randomness”.
    Can you help me make this clear?

    p/s: English is not my native language so… my English is not really good :P


Leave a Reply to Dave Cancel reply

