Flash Actionscript 101, The First ActionScript I Ever Learned – taterboy
December 21st, 2008 | Filed under: ActionScript 101, ActionScript 3, Flash, Flex, Tutorials

This is it, the very first bit of actionscript code I ever learned, besides play() and gotoAndStop() of course. The lesson went down with an experienced programmer looking over my shoulder telling me what to type. After this little app was finished, my brain hurt only understanding a few of the lines we wrote. That code was referenced and/or modified on more then a few projects that came after, each time deciphering more and applying it to new functionalities.

The original script was back in the day of AS1, but I am going to present it to you in AS3. If you are a beginner to ActionScript then it is the perfect time to learn AS3.

We are going to start really remedial for a minute and go over the basics of the classes and objects we will be using. It is kind-of long, so if you already have the basics covered, you can skip to the Application code.

The Variable:
Remember Pre-Algebra? 2+x = y? Variables are used for more then just place holders in a math equation. Programming is a very literal language, variables are how we make it figurative. Now instead of addressing one object with a snippet of code, that code can be applied to the many objects and properties our variables represent.

To use a variable, we must declare it using these three letters “var”. Then comes the creative part, we get to think of a name. This can be a lot of fun making up funny names for things until someone else has to figure out your code or you forget that you called the variable that is going to bring balance to your application “anakin”, oops, or was that “luke”?

After naming the variable, we have to declare it’s type. We really don’t have to, but it is a good idea. This variable will be a Number, because we will need it to include decimals.

Here are some examples of how variables can be used. Think about if we were selling apples that costs 65¢ a peace. A person wants to buy 5 apples. so we build an equation to handle the transaction.

?View Code ACTIONSCRIPT
var totalCost:Number;
totalCost = 0.65 * 5; //3.25

Ok, so we went conservitive, using “totalCost” for the total of apples purchased. Now what do we do when someone wants to buy 4 apples, or 6, or 8? Now we should add a new variable to represent the amount of apples. This variables declaration is an “int” (integer) as we will not be selling fractions of apples.

?View Code ACTIONSCRIPT
var numApples:int = 5;
var totalCost:Number;
totalCost = 0.65 * numApples; // 3.25

Everyone is happy until next week when there is an apple shortage and the price increases to 85¢ a piece. Now you have to go through you app and change all the prices from 65¢ to 85¢. If we use variables we can easily modify the app when the price changes, better yet, now this same app could be used to handle bananas, grapefruit and pears which all have different prices.

?View Code ACTIONSCRIPT
var cost:Number = 0.85;
var numFruit = 5;
var totalCost:Numer;
totalCost = cost * numFruit; // $4.25

Array:
Array is one of the most powerful classes in Flash. It’s power comes from the way an array holds a collection of information. Not only do we have access to the information, but we can loop through all the items in an array and monitor the length of the collection.

This is how we might set up some variables without arrays. If we add or take away an item, we have to update a separate variable to keep track of the total amount. Looping through this is information is possible, but tricky.

?View Code ACTIONSCRIPT
var fuit1:String = "apple";
var fruit2:String = "banana";
var fruit3:String = "pear";
var fruits:int = 3;
 
// Or we can do the same thing with an array.
 
var fruitArr:Array = ["apple","banana","pear"];
 
trace(fruitArr[0]); //"apple
trace(fruitArr.length); //3

One thing that you must remember when using arrays is that they are zero indexed, meaning the first position in the array is 0. This can cause a little confusion because we teach our children to start counting at 1, not 0. This will hopefully make more sense later or maybe more confusion, but at least you will know why you are confused.

Tip: instead of useing var fruitArr:Array = new Array(); which you may have seen before. Using the square braces will do same thing. var fruitArr:Array = [];

If we think of our application as if it were an engine, the data objects (arrays, XML) are the fuel. The part of the application that interates like loops, enter frame events and timers are the heart of the engine, like the pistons, cams and crank shaft. This engine starts once the app loads and runs until we stop everything or close the app.

for() Loop:
Interates or repeats a a specified amount allowing our engine to apply the same code to multiple objects. Loops will run and complete in between each frame, before each render. This means you will not visually see what the loop is doing until it completes and the stage renders.

?View Code ACTIONSCRIPT
// This is a loop using the array from above:
for(var p:String in fruitArr){
	trace(fruitArr[p] + " | index = " + p);
}
 
output:
apple | index = 0
banana | index = 1
pear | index = 2

First we assign a variable to the item that is going to loop trough the array. p stands for property and is a string. Here you can see the output of “p” which is showing the index or location of each item in the array. Notice that “apple” is the first item, which has an index of 0. If we get the length of the array (fruitArr.length) it will return a 3 which is 1 more then the last index in the array (2). Length counts like we do, starting at #1, index counts like computers do, starting at 0.

Tip: The p variable outputs a number in this case. This number is not really a number, it is a string using number characters. If we tried to add these “numbers” up, we would get “012″ instead of the sum of 3. This is one reason declaring variable types are important. The compiler will tell us immediately if we are passing a string into an equation where a number or integer should be. Many external data sources will pass numbers into Flash as strings. Declaring variable types adds integrity to our applications.

Function:
A function is like a little wrapper or snippet of code that we can call at a later time. They are like the transmission, servos, clutch and any other metaphorical mechanism that takes energy and makes stuff happen.

Functions can run with or without feedback, adding a few arguments they can become very flexible. Let’s use our fruit price calculator equation as a sample. This function receives two arguments (quantity and price), does the calculation, then returns the price. Nothing happens when the script loads, only when the function is called, see below.

?View Code ACTIONSCRIPT
function chaChing(quantity:int, price:Number):Number{
	var calc:Number = price * quantity;
	return calc;
}
var totalCost:Number = chaChing(5, 0.85);
trace(totalCost); //$4.25
 
// Notice the declaration :Number after the close parenthases
// on the function name.
function chaChing():Number{
}
 
// This lets the compiler know that the function is returning
// a value when it is called. If we do not need to return a value
// when the funciton is called, we would use void.
 
function chaChing():void{
}

This is a really simple one line function, but even this is a valid use. If you ever use the same equation or sequence more then once in your application, wrap it in a function.

Tip: A variables declared inside of a function will not be accessable outside of that function, but variables decaleared outside of the function are visible to it.

Tip: The words method and function are interchangeable.

Tip: Most “Real” programmers will put the opening curly brace one the next line under the function name.

if / else Condition:
Basically a switch, if a cindition is met, do one thing, if not then do something different.

Event:
These enable our controls and is the triggering system for our functions. Events monitors the engine and user input, they can be considered part of the engines electrical system.

Finally the Application:
The simple application we are going to build is an image loader. We will build a custom button, the code will place a button on the stage for each image. We will then hook up these controls to dynamically load in each image.

The beginning of our app is the config area, this is where we set up all of our variables and any constants.

?View Code ACTIONSCRIPT
/*
* first is the array, this is a list of image urls.
* We are going to loop through this array to create the correct amount of buttons.
* When the buttons are pressed, we will use the array to pull to corresponding image url.
*/
var imageArr:Array = ["images/apple.jpg","images/banana.jpg","images/pear.jpg"];
 
 
/****************************************************
* variables
****************************************************/
// buffHeight: will be use this to calulate the y possition of each button.
// 22 is the y coordinate to start the first button.
var buffHeight:int = 22;
 
// loadX and loadY: This will place our image in the correct spot on the stage. 
var loadX:int = 156;
var loady:int = 22;
 
/****************************************************
* the loop:
* Iterates through the array, adds a button for each item, adds event listeners,
* updates the buffHeight variable then stops when it reaches the end of the array. 
*****************************************************/
 
// There are a few different types of loops, this one is based on the items of an array. 
// The first part of the loop conditions is declaring a variable to represent the index 
// as the loop iterates through the array.
 
for(var p:String in imageArr){
 
	// create new ImageButton
	var imgBtn:ImageButton = new ImageButton();
 
	// add a button label
	imgBtn.labelText.text = "Image " + p;	
 
	// give the button a id from "p" which references the index
	// of the current item in the array.
	imgBtn.id = int(p);
 
	// set the y property using the buffHeight variable.
	imgBtn.y = buffHeight;
	imgBtn.x = 20;
 
	// add the eventListener to capture the button clicks
	imgBtn.addEventListener(MouseEvent.CLICK,clickHandler);
 
	//add the button to the stage.
	addChild(imgBtn);
 
	//update the variable with the height of this button, so the next button's y position will be below it.
	buffHeight += imgBtn.height + 5;
}
 
/****************************************************
* function clickHandler(MouseEvent)
* handler for the Click MouseEvent assigned to each button in the loop.
****************************************************/
function clickHandler(ev:MouseEvent):void{
 
	// the event's target property tells which button fired the event, now we can get the correct id.
	var id:int = ev.currentTarget.id;
 
	//use the id and the imageArr to get the correct image url.
	var url:String = imageArr[id];
 
	//call the loadImage function with the url as an argument.
	loadImage(url);
}
 
/****************************************************
* function loadImage(url:String)
* function for loading the images
****************************************************/
function loadImage(url:String):void{
 
	// new variable of new loader object
	var ldr:Loader = new Loader();
 
	// new URLRequest using the url we passed in as an argument.
	// this converts the string into a url request we can pass to the loader to load the image.
	var req:URLRequest = new URLRequest(url);
 
	//loading the image
	ldr.load(req);
 
	ldr.x = loadX;
	ldr.y = loady;
 
	// add loader to MovieClip referenced by loadTarget.
	addChild(ldr);
}
 
stop();

Button code and instructions:
Make a new MovieClip. Inside this new MovieClip create some artwork to be used as the button background. Add a textField and variable declaration for id (we will pass in the id during the loop). Then check the Export to ActionScript option in the MovieClips *properties window.

*To get to the MovieClips property window, right-click on the MovieClip in the Library, then choose properties. You may need to click the advanced button to see all the options.

We are using a MovieClip instead of a button, so that we can pass in an id and control the text. So we are going to build a MovieClip to act as a button.

Source Here

Where to go from here:
1. Play with the application variables and the array. Expand the app by giving each button a better name. Maybe build the array using names in stead of urls, then you can create the new url string using “images/” + name + “.jpg”. You could also create a name array in the same sequence or use slice on the url to pull the name out.

2. Expand the buttons, if you really want to get fancy, create an on-state for each button, so that you can tell which image is currently displayed.

3. Add the calculator code to display how much each item cost when you click a button and a loader.

Tip: The ldr function above places one item on top of another, this may cause an issue if you want to show something behind each image while it is loading.

Take the existing code and come up with another uses for it. If you come up with some cool ideas, post some links below. Also if you figure out any of the previous enhancement, post some code.

To put your code in a code block, you can wrap it in these tags. Take out the “[" and "]” ,square brackets.
[<]pre lang=”actionscript”[>]
// all code goes here.
[<]/pre[>]

Technorati Tags: , , , , ,

Other Related Articles:

|

5 Comments »

  1. WOW! Great post, especially for a newbie like me`-`
    I found a typo, or at least I could not get it working until I changed fruit to fruitArr in the for() Loop: section.

    Thanks so much for making this post, I feel thank to you that I am actually understanding As 3`-`

    Next I have to learn how to make such a cool interface too`-`

    Thanks,
    Johnny

    Comment by John — March 1, 2009 @ 3:30 am

  2. Thanks for catching that, I really need a good editor. Typos, are one of the biggest bug creators.

    Comment by taterboy — March 2, 2009 @ 7:08 am

  3. Yeah I know what you mean, typos are so easy to make. I am glad I caught it too`-`
    Can I ask–> how would I change the numbering to not include the first array item as 0? That is to have 1,2,3 instead of 0,1,2?

    I see in the As code that there is :
    // add a button label
    imgBtn.labelText.text = “Image ” + p;

    // give the button a id from “p” which references the index
    // of the current item in the array.
    imgBtn.id = int(p);

    I tried using “p+1″ in step up one number but no luck.

    Thanks so much for showing these examples on your blog`-“
    Johnny

    Comment by John — March 2, 2009 @ 10:25 pm

  4. p is declared as a string, it is the only variable type the “in” for loop will except. We can parse p into an number or integer in most cases like this.

    int(p) or Number(p).

    int(p) + 1; should give you a number sequence starting with 1.

    If that does not work, then you can always add a new variable to count up for you. Before the for loop declare a new variable like this.

    var arrCnt:int = 1; // set the starting number
    for(var p:String in imageArr){
    // use the arrCnt variable to make id an integer starting at 1.
    imgBtn.id = arrCnt;
    // increase arrCnt every cycle of the array; 1,2,3,4,5,6
    arrCnt ++;
    }

    Comment by taterboy — March 3, 2009 @ 6:37 am

  5. Hi,
    WOW! Thanks so much, this took a while for me to figure out, but I got it`-`
    First I think that I got a index out of bounds error, as when I was clicking on 3 there was no reference, as the array only goes to 2, since it starts at zero. I was using imgBtn.id = int(arrCnt); instead of what it should be imgBtn.id = int(p); as we are only using the new variable arrCnt has the display number and not the variable p which holds the items in the array? Not sure if I say that right, but below is the whole loop, and how I got it working:

    var arrCnt:int = 1; // set the starting number

    for(var p:String in imageArr){

    // create new ImageButton
    var imgBtn:ImageButton = new ImageButton();

    // add a button label
    imgBtn.labelText.text = “Image ” + int(arrCnt);

    // give the button a id from “p” which references the index
    // of the current item in the array.
    imgBtn.id = int(p);

    // set the y property using the buffHeight variable.
    imgBtn.y = buffHeight;
    imgBtn.x = 20;

    // add the eventListener to capture the button clicks
    imgBtn.addEventListener(MouseEvent.CLICK,clickHandler);

    //add the button to the stage.
    addChild(imgBtn);

    //update the variable with the height of this button, so the next button’s y position will be below it.
    buffHeight += imgBtn.height + 5;
    arrCnt++
    }

    Thanks so much for your help`-`
    Johnny

    Comment by John — March 3, 2009 @ 10:44 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment