Home > Blog > AS3 Tutorial – Math.random()

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.

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!
}

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% [?]

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • LinkedIn
  • Mixx
  • Google
  • Technorati
  • Print this article!
  • E-mail this story to a friend!
Rate this Post:
1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.89 out of 5)
Loading ... Loading ...
 

10 Comments

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

  4. Ryan

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

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

  6. Ryan

    Ryan – thanks for your request! i’ll get right on it.

    - Also Ryan

  7. Guy

    Good job man. Helped e more than most tuts! Keep it up. God bless

  8. 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);
    // 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 ^_^

  9. 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…

  10. Pooja

    good tutorial…..Thanks

Leave a Comment




Your Comment