Display random background
March 29th, 2009 in Flash | 6 CommentsEach time the user will load the swf file, a random background will be displayed.
This process is done very quickly and is based on the random method of the Math class.
1. We have included a start file in the source, so first download it.
2. Open randomBg_begin.fla and explore it.
There are 3 layers, the top one for the actions code, the second for the content which is simple text over a transparent rectangle.
The third is the backgrounds layer, select it. On the stage there is a MovieClip of instance name bg_mc, double click on it. You can see that the movie clip contains three frames, each one with a different pattern.

3. Return to Scene 1 so that you can add the code. Select the first frame of actions layer and open the actions panel (F9).
Paste the following code :
var bg_number : Number = 3; var choice :Number = Math.ceil(Math.random()*bg_number); bg_mc.gotoAndStop(choice);
4. Yes, just three lines of code, as simple as this.
The variable bg_number stores the number of different backgrounds.
We want to choose randomly between our 3 backgrounds which one to display so we need to get the number 1 , 2 or 3.
To do this we call the random method that returns a pseudo-random number n, where 0 <= n < 1 and multiply it by bg_number .
To obtain a ceiling value, we call the ceil method of the Math class.
Finally the gotoAndStop method takes the value choice as parameter.
5. Test the application by pressing Ctrl + Enter on Windows or Cmd + Enter on Mac. Test it several times to see the different backgrounds.






May 23rd, 2009
Very useful article, im using this tutorials in my site also,
with this sites name,
Jun 26th, 2009
Good stuff.
thanx
Jul 21st, 2009
hey just found your site and have been scroling through – your content is very high quality and have managed to find a few gems (mainly action script 3). I am making the transition from as2 to as3 and i think this site will help a great deal.
: )
Jul 22nd, 2009
[...] Read tutorial [...]
Nov 17th, 2009
Wow. this is the second time i’ve programmed a random background and this version was infinitely easier that the way I did it before. Nice job. Works beautifully.
Dec 13th, 2009
Nice one, but is there a way to use images that on a server, for exmple:you go into server`s folder and change required images without having to compile and upload a new version of a viewer?