Flash Actionscript Goodies
Heres a few helpful bits or flash actionscript code to help you on your way with developing dynamic flash content.
Random Number
There are a few ways to generate a random number in flash it all depends on what you need and how your going to do things, heres some examples:Generate a random number between 0 and 10
variable = Math.random()*10;
Result: variable = 7.967452
Rounding a Random Number
variable = Math.floor(Math.random()*10);
Result: variable = 7
Random Number (Between specific numbers 10-20)
variable = Math.floor(Math.random()*(20-10+1))+10;
Result: variable = 15
For/While Loops
Loops are useful because they allow you to cycle through variables without having to write mountains of code, heres an example of a simple loop for creating many different numbered variables each with a random number.
for (i=0;i<11;i++) {
var tempvar = "variable"+i;
_level0[tempvar] = Math.floor(Math.random()*30);
}
Remember once you define the letter (i) in the loop, it will display the value it has been given, in this example (i++) means that it will add 1 to (i) each time, (<11) means this loop will stop after (i) hits 10. The Output for the above is as follows:
variable1 = 23
variable2 = 17
variable3 = 3
variable4 = 9
variable5 = 22
variable6 = 12
variable7 = 6
variable8 = 9
variable9 = 10
variable10 = 30
Key Listeners
Key Listeners allow you to record the input of keys from the keyboard in flash and allow you to peform actions with keys
First you need to setup your key listener as a function as follows:
KeyListener = new Object();
KeyListener.onKeyDown = function() {
if (Key.getAscii() == 13) { // Code for ENTER key
gotoAndPlay(25);
} else if (Key.getAscii() == 8) { // Code for BACKSPACE key
gotoAndPlay(35);
}
}
Then either after the function or on another frame where you want the key listender to start simply add this code:
Key.addListener(KeyListener);
Technorati Tags: Flash Actionscript Goodies