Beginning Actionscript 3

Starting out with any programming language is difficult to grasp at first. What you will find however is that after learning the concepts behind one language, it gets easier when you move to another language (Javascript, PHP…).

The following are just a few examples of the simplest code you can write to help with understanding the syntax of ActionScript 3 as well as the logic in programming in general.

To begin writing and testing this code you will need to open and save a new file (call it something like “ProgrammingBasics.fla”) then select the first keyframe of your movie and go to Window>Actions (or hit the F9 key) to view your Actions window. When the ActionScript box pops up, be sure that Script Assist is not turned on in the top right box and you can close the left side panel using the arrow in the middle of the pane if it is open.

Comments and Variables

Let’s start out by making something happen. In your scripting window, type the following:

trace("Hello World!");

When we write the word “trace” with “()” next to it, what we are doing is calling the trace function. This is a function that is built into ActionScript and is meant to output data to the developer. In order to tell it what data to pass, we add a parameter inside the function (“Hello World!”). Whatever is inside the parameter is what will be in the output window.

Test the movie by going to Control>Test Movie (Ctrl+Enter). There should be nothing in the stage, however you should see an output window with the text “Hello World!”.

As you write your code, it is a good idea to add comments so when you or another developer go back to view the code it makes sense. To add comments to your code, add the following two examples:

//Single line comments are made with two forward slashes
/*
Long blocks of comments
Can also start with a forwardslash and asterisk and will not end
until you put an asterisk forwardslash
*/

This code will not be run, it is only used as notes to ourselves.

Eventually when we write our code, we will need to store the value of something. This could be text, a number, or something else. What we would use for this task is a variable. The way we can write a variable is as follows:

var firstname = "Jeff";

So we start with the word “var” to let ActionScript know we are about to define an new variable. We can then name the variable anything we want, just make sure not to include spaces. Be descriptive in your variable name so we know what value it stores later on. Next we just use the “=” operator to set the value of the variable to the string “Jeff”. The quotes around the text let ActionScript know to treat the text as just text and not a variable or number.

So now this variable holds the data “Jeff”. So if we trace that variable, in our output window that is the value that should be displayed:

trace(firstname);

We can create as many variables as we need in our program and use these values later on as needed.

We can also overwrite variables with new data later on in our code. As the program runs, it reads the code from top to bottom. So if we add the code below to our program and test it out, it will first output the text “Jeff”, and then output the word “John” as the variable changes.

firstname = "John";
trace(firstname);

Data Types

There are 3 main data types used in programming (strings, numbers, boolean). What we will see below is known as “strict data typing”, which defines what the variable type will be when we create it. This is useful for debugging our program, if at any point something that we define as a number for some reason becomes a string, we will be notified with an error.

Strings

We tell flash what data type our variable is by using :D atatype after initially defining the variable. So for example, our name variable would be…

var myname:String = "Jeff Kilroy";
trace(myname);

Numbers

The next data type is a number, and numerical value can be added to this variable

var mycoins:Number = 8;
trace(mycoins);

If I now try to put a string in here, it will cause an error (So make sure to use “//” and comment it out when you are done testing it out)

mycoins = "Hi!";

So why cant we make mycoins a string? Like this: var mystringcoins:String = “8″;. Well, the great thing about number variables, is we can do math!!!

trace(mycoins*5);//Multiply my coins by 5

Boolean

The last main data type is known as a Boolean variable. Don’t let the tricky name fool you, it just means true or false.

var awake:Boolean = true;
var drunk:Boolean = false;
trace(awake);
trace(drunk);

So remember, once you set a variable to a specific data type, you cannot make it a different data type.

Operators

Operators in Flash as well as other programming languages are symbols that perform some sort of function. There are many operators in flash, you can view a list of them here:

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/operators.html

For now we are only going to use very basic math and string operators

Concatenation

Concatenation is to take two strings and merge them together using the plus (+) symbol, so if we have the following two variables:

var fname:String = "Jeff";
var lname:String = "Kilroy";

We might want a variable that merges the two variables to represent a full name

var fullname:String = fname+lname;
trace(fullname);

We can also concatenate non-variable strings (notice the space character in quotes to add space between the two names):

fullname = fname+" "+lname;
trace(fullname);

We can also concatenate strings and variables inside the trace function, this helps us debug and understand what is being outputted to us:

trace("My Name: "+fullname);

Math

Using mathematical symbols (+, -, *, /) we can do math between number variables

var totalclasses:Number = 16;
var classestaken:Number = 12;
//Subtraction:
var classesleft:Number = totalclasses-classestaken;
trace("There are "+classesleft+" classes left!");
//Addition
trace(totalclasses+classestaken);
//Multiplication
trace(totalclasses*classestaken);
//Division
trace(totalclasses/classestaken);

Functions

Remember kids, you can’t spell function, without fun!

Functions are essential in AS3 as well as all programming languages. A function is essentially a block of code that can be used anytime you want. We define a function like this:

function givemessage():void{
 trace("Hello!");
 trace("This was made with a function!");
}

So lets look at that code bit by bit
function
Just like when we define a variable we begin with the word “var”, when defining a function we begin with the word “function”. This tells flash we are about to make a new function.

givemessage
Again, just like when making a variable, I can make a function have any name I want. You want to describe what your function is doing so it is easy to find later when you are working on it

()
Every function has opening and closing parenthesis after it’s name this is how both we and flash know that it is a function and not a variable.

:void
This is where we begin again strict data typing. There will be instances later on where we will ask our function to return a value to our code. It could be a Number, a String, or something more advanced and if that were the case, we would change the data type. In this case, all we are asking is that the function run normally, and since it does not return any value back to our code, we put “:void”

{” AND “}
The opening and closing brackets let us know where our function begins and ends everything between the opening and closing brackets runs when we tell our function to start. It is a good idea to indent the code in-between the brackets, it makes the code more readable and let’s us know right away that the two trace scripts are inside the function we made

Why didn’t our function work???

Well we defined our function, but did not run it yet. Now that we made our function, we can run it any time we want by writing the function name, followed by parenthesis, here we will call it a few times:

givemessage();
trace("");
trace("We can now call this function whenever we want");
trace("------------------");
givemessage();
givemessage();

Flash has many built in functions, two of them we have already used! Now that you know how to find functions by looking for “()”, you should be able to detect what two functions we have already used…

stop(); AND trace();

Both of these are functions built in by Flash. We can tell because they end with “()” These are also sometimes called methods. While there is a technical difference between the terms method and function, for now it is okay to assume they mean the same thing

Parameters

Parameters are values that can be passed to our function. We already have used parameters! When you put something in between the parenthesis of a function name, you are sending a parameter to the function. We do this with trace:

trace("This is a parameter");

We can also set up our function to accept parameters. To do so, we create a variable inside the parenthesis when we define our function

function sayhi(username):void{
 trace("Hello "+username+"!");
}

We now put a variable in between our defined function parenthesis in our trace we used that variable to say hi to the user so now to call this function, we need to pass a parameter for the function to see

sayhi("Jeff");

We can also put variables in our parameter, similar with how we use trace

var myname = "Jeff";
sayhi(myname);
myname = "Joe";
sayhi(myname);

So how will functions be useful?
There are many many many reasons we would use a function:

  • If we have a block of code that we will use many times in our script
  • If we have code that needs to be run after a certain action happens
  • If we have code that will only change slightly depenting upon certain variables (parameters passed)

Conditionals and Loops

Conditionals

In most programs, we will get to a point where we need to detect something. We do this using an “IF STATEMENT“. We will basically be asking “IF (x) equals (y), then perform this action”. Let’s take a look at how we would do this in actionscript. Below we will start by defining a variable and then create the if statement. Note that it looks much like a function, containing the parenthesis where our conditional goes. Then between the brackets we write what is called if the condition is true

var favoritecolor = "blue";
if(favoritecolor == "blue"){
trace("The color is blue!");
}

Here we have a new conditional! “==” essentially means “…is equal to…” Be sure not to just use “=” (only one equal symbol) or it will always return true.

Alternatively we can use “!=” to detect if something “…is not equal to…”

if(favoritecolor != "red"){
trace("The color is not red");
}

Two more operators to help us construct our statement:

  • “&&” We can put two if statements together and determine if they ALL are true
  • “||” We can put two if statements together and determine if ANY of them are true
if(favoritecolor != "orange" && favoritecolor != "blue"){
trace("You will never see this message because 'favoritecolor' cannot be both blue AND orange");
}
//
if(favoritecolor != "orange" || favoritecolor != "blue"){
trace("'favoritecolor' is either orange or blue");
}

Suppose we need to check multiple if statements to determine what action to take. We use the “else” statement to perform an action to any other possibility

if(favoritecolor == "red"){
trace("The color is red");
}else{
trace("The color is not red");
}

Finally, we can combine multiple if statements to determine the action to take using else if…

if(favoritecolor == "red"){
trace("The color is red");
}else if(favoritecolor == "green"){
trace("The color is green");
}else if(favoritecolor == "brown"){
trace("The color is brown");
}else{
trace("The color is something else");
}

Loops

Loops are used when we want to run one or more lines multiple times. Take a look at the example below

for(var i = 0; i<10;i++){
trace("Loop #"+i);
}

So when you test this out you should see an output saying from Loop #0 to Loop #9. The structure will look similar to an if statement or a function, where we have a condition in the parenthesis and between our brackets we have the code to run.

The difference here is in the condition there are three separate sections:

  1. We setup a new variable to use “i” and set our start value “0″
  2. We define how long we want the loop to run “as long as i is less than 10″
  3. What happens after each loop “increase i by 1″

This entry was posted in Tutorials. Bookmark the permalink.

One Response to Beginning Actionscript 3

  1. Allan says:

    Great article. Waiting for more.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


6 × two =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">