Tutorials » Actionscripting: Loading a different image each time using Local Shared Objects - Page 4
Random Image
In order to generate random numbers in Flash you use Math.random(). This method returns a number x, where 0 <= x < 1.
Usually you want to generate a random integer n, where 0 <= n < max and max is also an integer.
This can bedone with Math.floor(Math.random() * max);
For example,
Math.floor(Math.random() * 5)
generates the numbers 0, 1, 2, 3 and 4.
More generally, Math.floor(Math.random() * (max - min)) + min generates a random integer n, where min <= n < max and min and max are also integers.
By testing the following piece of code you'll get the numbers 2, 3 and 4:
import flash.events.Event;
var max:uint = 5;
var min:uint = 2;
var rand = Math.floor(Math.random() * (max - min)) + min;
addEventListener(Event.ENTER_FRAME, traceRandom);
function traceRandom(e:Event)
{
var rand = Math.floor(Math.random() * (max - min)) + min;
trace(rand);
}
For the non-repetitive random image, you need to make sure the new number is different from the last one. For this I created the following recursive function which ensures that the random number is always different from n. Obviously, total has to be greater than 1, i.e., you have to have more than one image, otherwise this doesn't make sense, and this code explodes!
function randomNumber(n:int):uint
{
var rand:uint = Math.floor(Math.random() * total);
if (rand == n)
return randomNumber(n);
else
return rand;
}
This LSO has a different name - random - so that there are no conflicts with the previous example, but the rest of the code is practically the same. You just need to call randomNumber(). This is the code available in MainRandom.as:
// create a LSO identified by "random"
var lso:SharedObject = SharedObject.getLocal("random");
var current:uint;
// does "current" exist already
if (lso.data.current != undefined)
{
// grab it
current = lso.data.current;
// create a new one, different from the previous
current = randomNumber(current);
}
// if it doesn't, create a new one
else
{
// it can be any number
// all random numbers are different from -1
current = randomNumber(-1);
}
// store current in the LSO
lso.data.current = current;
// load the appropriate image
loadImage(current);
Everytime that you refresh the browser or test the movie, you'll get a different image from the previous one. In this case you can get image A, then B and then A again.
All the files are available for download here.
| » Level Intermediate |
|
Added: 2011-02-28 Rating: 0 Votes: 0 |
| » Author |
| Nuno Mira has been a Flash Developer for 9 years. He loves teaching, and learning. When he isn't coding he may be surfing or snowboarding. |
| » Download |
| Download the files used in this tutorial. |
| Download (491 kb) |
| » Forums |
| More help? Search our boards for quick answers! |
-
You must have javascript enabled in order to post comments.


Comments
There are no comments yet. Be the first to comment!