Archive

Posts Tagged ‘tips’

Useful Functions (Tips)

September 1st, 2009 Matthew Lodge No comments

The following code generates an array then adds all the numbers in the array together. Really quite useless.

However the methods used to create this snippet are extremely useful.

Here I break them down.

var randomNumber:int = new int();
var myArray:Array = new Array();
var total:int = new int();
var totalNumbers:int = new int();
totalNumbers = 10;
First of all I declare some variables by doing this the variables can be used in and outside of functions. This is called variable scope
function generateNumbers(){
 for(var i:uint; i<totalNumbers; i++){
Here I start a loop with a variable as the number to count to. This lets you modify the code easily
randomNumber = Math.ceil((Math.random()*(5^i^3)));
Here is the code that generates the random numbers. Math.ceil() rounds the numbers up to an interger. Math.random() generates a random number with is then multiplied by 5 to the power of "i"
myArray.push(randomNumber);
The push() function in an array add the value in the argument as a new value in the array.
}
 for(var il:uint; il<totalNumbers; il++){
 total += myArray[il];
Here the variable "il" counts up until it equals "totalNumbers" whilst it does that it cycles through the array and adds the values to the variable "total" using the operator +=
}
}
generateNumbers();
Calling the function
trace(myArray);
trace(total);
Here I trace to the output panel in flash to check the function is working. It is useful for debugging to put trace() functions in to see where the code is failing So as you can see AS3 has many useful functions to help cut the time spent coding. Use these and you're on your way to becoming an ace programmer.
Categories: Actionscript 3 Tags: , , ,