SIM1 - Class 05 - 2011

Subject SIM1 - Interactive Media 1
Competencies

BSBINN502A.1 - Build and Sustain and Innovative Work Environment (part 1)
CUFDIG506A.1 - Design Interaction (part 1)

Course Title ADVANCED DIPLOMA of SCREEN AND MEDIA (CUF60107)
Teacher Lisa Cianci - email: lisa.cianci@vu.edu.au
Class Website: http://lisacianci.vucreativeindustries.com/2011/SIM1
                         (username & password = student)

 

Flash introduction to ActionScript 3

Today we will be covering the following topics:

 

Button Symbols

Button symbols are actually a special type of four-frame interactive movie clip. When you select the button type when creating a symbol, Flash creates a Timeline with four frames. The first three frames display the button’s three possible states, Up, Over, and Down; the fourth frame defines the active area of the button.

The button symbol timeline doesn't actually play linearly like a normal timeline; it reacts to mouse pointer movement and actions by jumping to the appropriate frame. To make a button interactive, you place an instance of the button symbol on the Stage and assign actions to the instance. You assign the actions to the root timeline of the of the Flash file. If the button is inside a movie clip, you can add the actions to the movie clip timeline. Do not add actions to the timeline of the button symbol. 

Each frame in the Timeline of a button symbol has a specific function:

Many Developers use movieclip symbols as buttons because of the higher level of control you can have with movieclips and their properties, but button symbols do have their uses - and can be an easy way to add interactivity to a Flash piece - without using much ActionScript at all.

We will have a play with the button symbol today and try some different examples incorporating tweening and sound.

Some examples of what you can do with buttons...

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

 

Introduction to AS3

What is ActionScript 3 (AS3)?
ActionScript is the programming language for the Adobe Flash Player and Adobe AIR run-time environments. It enables interactivity, data handling, and much more in Flash, Flex, and AIR content and applications.
ActionScript is executed by the ActionScript Virtual Machine (AVM), which is part of Flash Player and AIR. ActionScript code is typically compiled into bytecode format (a sort of programming language that’s written and understood by computers) by a compiler, such as the one built into Adobe Flash CS4 Professional or Adobe Flex Builder, or that is available in the Adobe Flex SDK. The bytecode is embedded in SWF files, which are executed by Flash Player and AIR.
ActionScript 3.0 offers a robust programming model that will be familiar to developers with a basic knowledge of object-oriented programming.

 

Programming fundamentals
Since ActionScript is a programming language -if you first understand a few general computer programming concepts, it will help you to learn ActionScript.


What computer programs do
First of all, it’s useful to have a conceptual idea of what a computer program is and what it does. There are two main aspects to a computer program:

•A program is a series of instructions or steps for the computer to carry out.

•Each step ultimately involves manipulating some piece of information or data.

In a general sense, a computer program is just a list of step-by-step instructions that you give to the computer, which it performs one by one. Each individual instruction is known as a statement. As you'll see throughout this manual, in ActionScript, each statement is written with a semicolon at the end.

In essence, all that a given instruction in a program does is manipulate some bit of data that’s stored in the computer’s memory. In a simple case, you might instruct the computer to add two numbers and store the result in its memory. In a more complex case, imagine there is a rectangle drawn on the screen, and you want to write a program to move it somewhere else on the screen. The computer is keeping track of certain information about the rectangle—the x, y coordinates where it’s located, how wide and tall it is, what colour it is, and so forth. Each of those bits of information is stored somewhere in the computer’s memory.

A program to move the rectangle to a different location would have steps like “change the x coordinate to 200; change the y coordinate to 150” (in other words, specifying new values to be used for the x and y coordinates). Of course, the computer does something with this data to actually turn those numbers into the image that appears on the computer screen; but for the level of detail we’re interested in, it’s enough to know that the process of “moving a rectangle on the screen” really just involves changing bits of data in the computer’s memory.

 

Where does the code go?

In the Flash authoring environment, you can add ActionScript code to any frame in a timeline. This code will be executed while the movie is playing back, when the playhead enters that frame.

Placing ActionScript code in frames provides a simple way to add behaviours to applications built in the Flash authoring tool. You can add code to any frame in the main timeline or to any frame in the timeline of any MovieClip symbol. However, this flexibility comes with a cost. When you build larger applications, it becomes easy to lose track of which frames contain which scripts. This can make the application more difficult to maintain over time.

Many developers simplify the organization of their ActionScript code in the Flash authoring tool by placing code only in the first frame of a timeline, or on a specific layer in the Flash document. This makes it easier to locate and maintain the code in your Flash FLA files. However, in order to use the same code in another Flash project, you must copy and paste the code into the new file.

If you want to be able to use your ActionScript code in other Flash projects, professional Flash developers prefer to place their code in external AS files because this is the way Classes are created using Object Oriented Programming (OOP) in Flash. The code is more useable and reuseable, thus more efficient. By removing the code from the graphical elements in the FLA file, you can edit the AS file without opening the FLA file - which is preferable when working in a team environment.

 

Terminology

If you aren't familiar with programming or ActionScript, you will come across a few terms that you may not be familiar with. Don't worry, we will cover these in class as we go through the exercises and learn about AS3 in a practical way.

I have also provided a copy of the Flash AS3 Programming Manual (15Mb) which is a very detailed guide to AS3. You can refer to this guide at any time, and it gives good descriptions of terminology such as Variables, Instances, Objects, Classes, Methods, Data Types. These are all terms you will become familiar with through doing class exercises.

Let's begin today's exercise by creating a new file and saving it in the way a professional Flash developer would work.

Saving files - file management & publishing/testing SWFs

1. a new Flash AS3 file. We will be using a very specific folder structure today to save our FLA, SWF and AS files in different folders, so it's important to get this structure correct from the begriming.

2. Create the folder structure as follows: A folder called "classwork" or similar to put everything in today. 2 sub-folders called "source" and "deploy" - the FLA files will be created in the source folder and the published SWF files will be saved in the deploy folder. This is so that when uploading to the web, you only need to upload the deploy folder to your site. The source folder is for your working & development files. The source folder also has a sub-folder called "classes". This folder is where we will store our external ActionScript files which are text files with an .as extension - as you can see in the image below.

file structure

 

3. Once you have the correct folder structure, save your FLA file in the source folder and give it a meaningful name such as as3test1.fla.

4 To make sure your SWF files are being published to the deploy folder, go to the File menu and select Publish Settings. Change the SWF format option to "../deploy/as3test1.swf" - this will ensure the SWF is published to that specific folder rather than the default which is the same folder as the FLA.

 

publish settings

 

5. You can test your movie using CTRL-Enter (Mac Cmd-Enter) or select Publish from the File menu to check and see if your SWF file is being saved in the deploy folder.

Now we are ready to start some coding.

I have provided a basic FLA file for us to work with today to speed up the process and make sure everyone is at the same place. Take a copy of as3exercise.FLA and make sure you save it in your source folder. Check the Publish Settings to make sure the SWF will be copied into your deploy folder.

This sample file contains an animation inside a movieclip and some buttons, plus keyframes on frames 1,10,20 & 30. It contains no ActionScript code - we will be adding some first to the timeline on frame 1, and then later, creating an external AS file to learn how object oriented programming (OOP) works in Flash.

 

Comments & Traces

Open up the as3exercise.fla file and you will see 5 layers on the timeline. The top layer is called "scripts" and is empty. To place code on the frame click on the keyframe on frame 1 and hit the F9 key to launch the Actions Panel. You can also access it from the Window menu, but remembering the shortcut key will make things a lot faster. F9 is a toggle key for the Actions Panel so you can close it too if it's in the way when you are using the stage.

When placing code on the timeline, you must use the Actions Panel.

actions panel

 

ActionScript 3.0 code supports two types of comments: single-line comments and multiline comments. These commenting mechanisms are similar to the commenting mechanisms in C++ and Java. The compiler will ignore text that is marked as a comment.
Single-line comments begin with two forward slash characters ( // ) and continue until the end of the line. For example, the following code contains a single-line comment:

var someNumber:Number = 3; // a single line comment


Multiline comments begin with a forward slash and asterisk ( /* ) and end with an asterisk and forward slash ( */ ).


/* This is multiline comment that can span
more than one line of code. */

 

Tracing your code

We use traces to test and debug our code. a trace sends information to the Output panel and doesn't affect the animation in the timeline. Here is an example of a trace - if you put this on frame 1 and test the movie, you won't see it in the SWF file, but you will see the string of text appear in the Output panel.

trace("hello world!");

 

Basic timeline controls

To stop the timeline from looping, and keep it on frame 1, place a stop(); script on frame 1:

stop();

To stop the animation in the square, you can target the square by its instance name. select the square and take a look at the property panel to see the instance name for this movieclip - you MUST give movieclips and buttons instance names (UNIQUE instance names) if you want to control them with ActionScript. The square animation has the instance name "ani1". So to stop or play this movieclip timeline, use the following scripts:

ani1.stop();
ani1.play();

or to force the playhead to go to a certain frame try the following scripts:

gotoAndStop(10); //go to frame 10 on the main timeline & stop there
gotoAndPlay(20); //go to frame 20 on the main timeline & play on from there
ani1.gotoAndStop(5); //go to frame 5 of the ani1 movieclip instance & stop there

Usually these scripts go inside functions that are triggered by events (see below) such as mouse clicks. We will use timeline controls in today's exercise.

 

Variables

Variables allow you to store values that you use in your program. To declare a variable, you must use the var statement with the variable name. In ActionScript 2.0, use of the var statement is only required if you use type annotations. In ActionScript 3.0, use of the var statement is always required. For example, the following line of ActionScript declares a variable named "someVar":

var someVar;

If you omit the var statement when declaring a variable, you will get a compiler error in strict mode and run-time error in standard mode. For example, the following line of code will result in an error if the variable has not been previously defined:

someVar; // error if someVar was not previously defined

To associate a variable with a data type, you must do so when you declare the variable. Declaring a variable without designating the variable’s type is allowed, but creates all kinds of problems and generates warnings when you test the file. You designate a variable’s type by appending the variable name with a colon (:), followed by the variable’s type. For example, the following code declares a variable somevar that is of type int (integer):

var someVar:int;

You can assign a value to a variable using the assignment operator (=). For example, the following code declares a variable i and assigns the value 20 to it:

var someVar:int;
someVar = 20;

You may find it more convenient to assign a value to a variable at the same time that you declare the variable, as in the following example:

var someVar:int = 20;

Common variable data types we will use:

Let's type some different variables in the actions panel for frame 1 and then we'll trace them to the output window...


var myString:String = "Hello World!";
var myInteger:int = 50;
var myBoolean:Boolean = true;
trace(myString);
trace(myInteger * 2); // will calculate 50 x 2 = 100
trace("is today Monday? " + myBoolean);

Test your flash file to see what appears in the Output Panel.

Functions

Functions are blocks of code that carry out specific tasks and can be reused in your program. There are two types of functions in ActionScript 3.0: methods and function closures. Whether a function is a called a method or a function closure depends on the context in which the function is defined. A function is called a method if you define it as part of a class definition or attach it to an instance of an object. A function is called a function closure if it is defined in any other way.

An example of a function:

function outputCall(e:Event):void{
trace(myString);
}

 

Events

You may notice that when you test the Flash file, it just loops through the 30 frames and the buttons don't work. We need to create some code to control the animated square movieclip, and to control navigation between frames on the main timeline. Because the square movieclip has it's own timeline, we can stop and play this animation without affecting the main timeline, and vice-versa.

You can think of events as occurrences of any kind in your SWF file that are of interest to you as a programmer. For example, most SWF files support user interaction of some sort—whether it's something as simple as responding to a mouse click or keyboard key press, or something more complex, such as accepting and processing data entered into a form. Any such user interaction with your SWF file is considered an event. Events can also occur without any direct user interaction, such as when data has finished loading from a server or when an attached camera has become active.

Flash “listens” for events in your code using event listeners. Event listeners are the functions or methods that you write to respond to specific events. To ensure that your program responds to events, you must add event listeners either to the event target or to any display list object that is part of an event object’s event flow.
Here's an example of some event listener code, it follows this basic structure:

 function myButton1function(e:MouseEvent):void {
      gotoAndStop(1);
 }
 myButton1.addEventListener(MouseEvent.MOUSE_UP, myButton1function);

This code does two things. First, it defines a function, which is the way to specify the actions that will be performed in response to the event. Next, it calls the
addEventListener() method of the source object, in essence “subscribing” the function to the specified event so that when the event happens, the function’s actions are carried out. When the event actually happens, the event target checks its list of all the functions and methods that are registered as event listeners. It then calls each one in turn, passing the event object as a parameter.

To make our buttons work we will create event listeners to listen for mouse clicks and functions to perform certain tasks when we click on specific buttons.

We will create 7 event listeners - one for each button, and 7 corresponding functions that will be executed when the buttons are clicked.

Place the following code on frame 1

//stop the playhead of the main timeline on frame 1 otherwise it will play & loop
stop();
//set the buttonModes for movieclips as buttons so the cursor 
//note that button 7 doesn't need a button mode because it is a button symbol
// not a movieclip
myButton1.buttonMode=true;
myButton2.buttonMode=true;
myButton3.buttonMode=true;
myButton4.buttonMode=true;
myButton5.buttonMode=true;
myButton6.buttonMode=true;
//event listeners for global buttons & frame 1 buttons
myButton1.addEventListener(MouseEvent.MOUSE_UP,button1function);
myButton2.addEventListener(MouseEvent.MOUSE_UP,button2function);
myButton3.addEventListener(MouseEvent.MOUSE_UP,button3function);
myButton4.addEventListener(MouseEvent.MOUSE_UP,button4function);
myButton5.addEventListener(MouseEvent.MOUSE_UP,button5function);
myButton6.addEventListener(MouseEvent.MOUSE_UP,button6function);
myButton7.addEventListener(MouseEvent.MOUSE_UP,button7function);
   
//functions
function button1function(e:MouseEvent):void {
     gotoAndStop(1);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); } function button2function(e:MouseEvent):void { gotoAndStop(10);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); //reset the listeners for the animation myButton5.buttonMode=true; myButton6.buttonMode=true; myButton5.addEventListener(MouseEvent.MOUSE_UP,button5function); myButton6.addEventListener(MouseEvent.MOUSE_UP,button6function); } function button3function(e:MouseEvent):void { gotoAndStop(20);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); } function button4function(e:MouseEvent):void { gotoAndStop(30);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); } //button functions for animation control function button5function(e:MouseEvent):void { ani1.play(); } function button6function(e:MouseEvent):void { ani1.stop(); } function button7function(e:MouseEvent):void {
//to launch another web page from your flash file, use the URLRequest class var myURL:URLRequest=new URLRequest("http://www.google.com/"); navigateToURL(myURL, "_blank"); }
 

Test the file now to see what happens when you click the buttons. Note that each button or movieclip has a UNIQUE instance name. If you accidentally have duplicate instance names, your Flash file will throw errors to the compiler errors panel. As we go through the semester you will learn a lot about debugging code in Flash because everyone makes errors with their code. It's often a good way to learn about ActionScript! The smallest typo or any incorrect syntax will stop your code from working properly.

 

Naming Instances & Variables

There are some strict rules for naming instances and variables in Flash.

 

*Things to note: to make use of the "fullscreen" button in the Flash video FLV playback component in a browser window, you need to generate the HTML file in the Flash Publish settings and set the HTML to "Allow Fullscreen". You can test this, but be careful how you use it. In this exercise today, going fullscreen works well, but when you escape back to the normal size, you may find that your video remains on all screens. I haven't found a work-around for this bug yet without adding some serious code, but will keep trying.

 

The Document Class (external ActionScript code)

So while the code above works well on frame 1, the professional convention is to create an external AS file for the code. When you do this, you are creating a Class, and when you link all of this code to the FLA file document properties it's called creating a Document Class. There are many good reasons for creating external code including reusing the code for more than 1 Flash file, and for enabling smoother workflow in a team development environment.

A Class is an abstract representation of an object. A class stores information about the types of data that an object can hold and the behaviours that an object can exhibit. The usefulness of such an abstraction may not be apparent when you write small scripts that contain only a few objects interacting with one another. As the scope of a program grows, however, and the number of objects that must be managed increases, you may find that classes allow you to better control how objects are created and how they interact with one another.

The structure of the code in a Document Class is different to the way we just place it on frame 1 - there's more to it. We need to define certain things and structure the code in a certain way. This is what we'll do now...

1. Comment out all the code on frame 1 in a multiline comment /* ---- */.

2. Create a new ActionScript file. This is just a normal text file with the .as extension. You can edit this in Flash, but some developers prefer to use other applications to write their code.

3. Save the file as Main.as, and make sure you save it in the classes sub-folder of your source folder. Main.as is what developers usually name their Document Class file. Note: it must have an upper-case 'M' as it is a Class name.

4. Paste the following code into your Main.as file - this is the basic structure that all class files must have:


//Packages allow you to bundle class definitions together in a way that facilitates
//code sharing and minimizes naming conflicts. // if the AS file is in a folder called classes, you must add the path to the package

package classes{
// we must IMPORT all of the classes we will need for publishing
// these are some standard ones you may require

import flash.display.*; //this one contains the MovieClip class
import flash.events.*;

//define the class name - it must be the same as the file (Main.as)and is case sensitive.
//It MUST start with a capital letter

//Note that this class 'extends' the existing Flash MovieClip Class
//this means it can use all of the properties and methods of the MovieClip class
//and we don't have to code all of those behaviours ourselves

public class Main extends MovieClip {
//declare variables here


//constructor function - must have the same name as the class
//the constructor executes as soon as the flash file loads

public function Main():void {
// add code here init();
}
//methods - methods are a type of function that are bound to a class
private function init():void {
//add code here
}
}
}

When creating a Class file, you generally define:

We can now take the code from frame 1 of the FLA file and place it in the Main.as file - but we must put certain parts of the code in certain places:

The finished code looks like this:

//Packages allow you to bundle class definitions together in a way that facilitates 
//code sharing and minimizes naming conflicts. 
// if the AS file is in a folder called classes, you must add the path to the package
package classes{
     // we must IMPORT all of the classes we will need for publishing
     // these are some standard ones you may require
     import flash.display.*;//this one contains the movieclip class
     import flash.events.*;
     import flash.net.*;
     //define the class name - it must be the same as the file (Main.as)and is case sensitive. 
     //It MUST start with a capital letter
     public class Main extends MovieClip {
          //declare variables (Just some test ones here)
          private var myString:String="Hello World!";
          private var myInteger:int=50;
          private var myBoolean:Boolean=true;
          //constructor function - must have the same name as the class
          //the constructor executes as soon as the flash file loads
          public function Main():void {
               //it's common practice to create an init() (initialise) method 
               //for scripts that you want to call in the constructor
               init();
               //you may choose to break up your scripts into functions
               //according to how you want to use and reuse them
               //as logical chunks of code 
               traceMessages();
          }
          //methods
          private function init():void {
               //these scripts are all the statements we want to execute 
               //as soon as the flash file loads 
               //stop the playhead of the main timeline
               stop();
               //set the buttonModes
               myButton1.buttonMode=true;
               myButton2.buttonMode=true;
               myButton3.buttonMode=true;
               myButton4.buttonMode=true;
               myButton5.buttonMode=true;
               myButton6.buttonMode=true;
               //event listeners for buttons
               myButton1.addEventListener(MouseEvent.MOUSE_UP,button1function);
               myButton2.addEventListener(MouseEvent.MOUSE_UP,button2function);
               myButton3.addEventListener(MouseEvent.MOUSE_UP,button3function);
               myButton4.addEventListener(MouseEvent.MOUSE_UP,button4function);
               myButton5.addEventListener(MouseEvent.MOUSE_UP,button5function);
               myButton6.addEventListener(MouseEvent.MOUSE_UP,button6function);
               myButton7.addEventListener(MouseEvent.MOUSE_UP,button7function);
          }
          //traceMessage
          private function traceMessages():void {
               trace(myString);
               trace(myInteger*2);
               trace("is today Monday? "+ myBoolean);
          }
          //button functions for timeline navigation
          private function button1function(e:MouseEvent):void {
               gotoAndStop(1);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); } private function button2function(e:MouseEvent):void { gotoAndStop(10);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); //reset the listeners for the animation myButton5.buttonMode=true; myButton6.buttonMode=true; myButton5.addEventListener(MouseEvent.MOUSE_UP,button5function); myButton6.addEventListener(MouseEvent.MOUSE_UP,button6function); } private function button3function(e:MouseEvent):void { gotoAndStop(20);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); } private function button4function(e:MouseEvent):void { gotoAndStop(30);
//you must put the stopAll() sound mixer command in each global button
//otherwise the sound from the video on frame 30 will continue to play

SoundMixer.stopAll(); } //button functions for animation control private function button5function(e:MouseEvent):void { ani1.play(); } private function button6function(e:MouseEvent):void { ani1.stop(); }
//button function for web link using URLRequest class private function button7function(e:MouseEvent):void { var myURL:URLRequest=new URLRequest("http://www.google.com/"); navigateToURL(myURL, "_blank"); } } }

 

 

It looks like a lot of code, but when you break it down and add good comments to the file, it becomes easy to read and to understand what's going on.

Once you have created the Main.as file, you must link it to your Flash file. You do this through the Properties Panel - click on the area outside the stage to show the Document properties in the Properties Panel.

doc class

In the Class field, type the Class name with its path. In this case, Main.as is in the classes folder, so the path is written like this:

classes.Main

We use a dot syntax and we don't put the .as extension. Now Flash knows where to find the Document Class file.

When we publish the file now, Flash will compile the code in the AS file with the graphics and other information in the FLA file and create one SWF file in the deploy folder. You have just created your first ActionScript Class! When you upload to the web, you only need the SWF file for the user to access.

Save and test!

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

References for beginning with AS3

There are lots of tutorials online for starting out with ActionScript. If you're familiar with AS2, you can find tutorials on migrating your code skills from AS2 to AS3. If you're a coding beginner, some of the Adobe TV video tutorials are great, and you can easily find others just by searching for "Flash AS3 beginners tutorial" or similar terms.

 

Use any remaining time to work on your assessment task.