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

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.

Davegood tutorial. I love your site, couldn’t bookmark it quick enough. The animation in your navigation and all the hand drawn elements are amazing.

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

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

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

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

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

- Also Ryan

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

as3 beginnerThank 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 ^_^

as3 beginnerLOL 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…

Poojagood tutorial…..Thanks

MattThanks for this.

Fast and made sense.

RyanMatt – thanks! Would you believe that this article remains the most high-traffic page on my site?

Pingback: Randomly placing a child on the stage | kitstop.co.nz

conscienceHi!

How to get random letter? for example, you can get random color.

Math.random()*0xffffff

Ryanconscience: 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

conscienceThanks.

I made It with String.

var a : String = “qweertyiop[asdjhfmvxcjhgf”;

and take random letter from It. maybe it is faster?

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

CodyRyan,

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

RyanCody – 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.

BergenGood 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:

random():Number

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

// gives you 1, 2, 3, 4, or 5 by raising the decimal number

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.

FreddytotalAsteroids 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.:)

ShebbyThe post was a tutorial about using Math.random(), not how to build an asteroid game from start to finish.

JanikThanks a lot for this simple yet helpflul tutorial.

Cheers

Ryan Henson CreightonThanks, Janik!

JeffreyI 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:

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

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

Ryan Henson CreightonHmm … 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:

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

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

PeteI 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!)

Ryan Henson CreightonThanks, 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:

http://ai-depot.com/Tutorial/PathFinding.html

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

GuestCheapprobably the reason why this is your most popular post is because it appears first if you search “Math.random as3″ in Google…

Ryan Henson CreightonYes, but how did i GET there? i blame Flashkit.

HoangAgain, 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

sashIt doesn’t work with a range off [0.3, 0.9]

Ryan Henson CreightonPost authorPost thine code.