Introduction to
ActionScript
What is ActionScript?
9
Controlling the Timeline
Button Scripts
Working with Text Fields
Setting Variables and
Expressions
Controlling Movie Clips
Controlling Video with
ActionScript
Loading a Quiz into an Existing
Movie
INTRODUCTION TO ACTIONSCRIPT
WHAT IS ACTIONSCRIPT?
ActionScript is a programming language, very similar to JavaScript. The purpose of ActionScript
is to give instructions to your movie. These instructions are in the form of a script made up of a
statement or a series of statements that execute specific tasks. Statements are lines of code that you
a ach to either a Bu on, a Movie Clip, or a Keyframe. When the user clicks a bu on, the statements
a ached to that bu on are executed. When the playhead passes over a particular keyframe with a
script a ached, the statements a ached to the keyframe are executed. For example, the following is a
statement a ached to a keyframe:
stop();
When the playhead passes over this keyframe (wherever it may be on the timeline), the statement is
executed. In this case, this command instructs the playhead to stop at this point on the timeline.
Where Does the ActionScript Go?
There are three places you can assign actions:
Frame Scripts
You can place scripts on keyframes in the timelines of your movie. For good practice, you should
create a layer that you’ll use in your movie or movie clip to place your ActionScripts.
To create a frame script, create a keyframe on the frame where you would like to place the script and
press F9 to activate the Action panel. Your script will run when movie enters the frame where the
script is present.
Bu on Scripts
You can a ach scripts to bu ons that appear on the Stage. For your script to work on a bu on, you
need to create a handler that tells the bu on that it will be responding to certain events performed by
the user of the movie, such as a mouse click.
164
INTRODUCTION TO ACTIONSCRIPT
To create a bu on script, select the bu on that will be responding to your script and press F9 to
activate the Action panel. Your script will run when the user performs the action that is being
handled by the bu ons’ script.
Movie Clip Scripts
You can also a ach scripts to movie clips. There are a number of events that happen when a movie is
being played that movie clips respond to.
To create a movie clip script, select the movie clip that will be responding to your script and press F9
to activate the Action panel. Your script will run when the event that is being handled by the movie
clip’s script occurs.
The Actions Panel
To program in ActionScript, you need to use the Actions panel. On the le side of the Actions panel
is a list of Actions that can be added to a script, and the right side of the Actions panel is where you
will be creating scripts.
In this example, we are looking at a bu on script that has the movie go to frame 1 in a scene called
“MainMenu” when the user releases the mouse bu on.
165
INTRODUCTION TO ACTIONSCRIPT
ActionScript Functions
On the upper le side of the Actions panel is a list of ActionScript actions. These are built-in actions
in Flash that are designed to perform a number of different tasks. The actions are separated into
categories by the type of action they perform, such as Timeline Control, or Movie Clip Control.
Ge ing each of the different actions to work sometimes requires you to enter some information to tell
the action what to do, called parameters. Some actions, like the stop() action require no parameters,
where other actions, like the gotoAndStop() action require a number of different parameters.
166
INTRODUCTION TO ACTIONSCRIPT
CONTROLLING THE TIMELINE
One of the most important things to learn to do is to control the Timeline. There are a number of
different actions that allow you to stop the timeline, start the playback of the timeline, and jump to
different locations in the timeline and to locations in different scenes.
Action Parameters
gotoAndPlay() Frame or The frame parameter can be a frame number,
Scene, Frame or the label of frame. The label name needs
gotoAndStop() Frame or to match case, and needs to be in quotes. The
Scene, Frame Scene name parameter also needs to match
case, and needs to be in quotes.
nextFrame() (none)
prevFrame() (none)
nextScene() (none)
prevScene() (none)
play() (none)
stop() (none)
Exercise 9.1 – Controlling the Timeline
In this exercise, we’ll be working on an e-Learning project that explores the animals of the Amazon.
The art director has given us a partially assembled Flash movie that has all of the graphic assets we
need, and has some of the movie layout created.
To get started, we’ll add some frame scripts to control the playback of the movie, and we’re going to
add some frame labels to some of the frames in the movie to help us later when we add some bu ons
to our project.
1. Open the Flash movie Chapter9 / amazon_animals.fla from the student files.
The movie is designed with three scenes – a MainMenu scene, and Instruction scene, and a Quiz
scene.
167
INTRODUCTION TO ACTIONSCRIPT
2. Test the movie to see how it currently plays.
Because there are no timeline scripts, the movie plays each frame of the movie, one a er another.
It plays the one frame in the MainMenu scene, the three frames in the Instruction scene, and the
one frame in the Quiz scene.
3. Close the test movie window. Select the MainMenu scene.
You can select the scene from the Edit Scene drop-down menu on the top-right corner of the
Timeline, or you can display the Scene panel by pressing Shi -F2 or from the Window -> Design
Panels -> Scene menu.
4. Select frame 1 of the Actions layer and open the Actions panel by pressing F9. In this case we
want Flash to stop and wait for the user to do something at our menu, so we’ll want to add a
stop() action.
5. In the function list on the le side of the Actions panel, open the Timeline Control actions list
by clicking on it, then double-click on the stop() action in the list.
The stop() action is added to the script editing section of the Actions panel. Note that
a semicolon (;) is added a er the stop() action – this signals the end of a statement in
ActionScript.
6. Test the movie, then a er viewing, close the test window.
Notice how the movie stops playing on the first frame of the main menu. We’ll add the bu ons to
the main menu in the next exercise.
7. Switch to the Instruction scene in the movie.
We’re going to be adding stop() actions to each of the frames of the Instruction scene, as well as
adding frame labels to each of the frames to help us specify where we are going in our movie.
168
INTRODUCTION TO ACTIONSCRIPT
8. Select frame 1 of the Actions layer, and add a stop() action to the frame. Repeat this step for
frame 2 and frame 3.
9. Select frame 1 of the Labels layer. Open the Properties inspector and in the frame text box type
“Jaguar”.
10. In frame 2 of the Labels layer, enter “Margay” as the label, and in frame 3 enter “Marmoset” as
the label.
11. Save the movie. We’ll continue to use this movie in the next exercise.
169
INTRODUCTION TO ACTIONSCRIPT
BUTTON SCRIPTS
To allow the user to interact with our movie, we need to add ActionScript handlers and actions to the
bu ons in our movie. A mouse event occurs when the user interacts with a bu on. When an action is
added to a bu on you’ll need to specify the event handler that will activate the action.
Mouse Events
Event When it Occurs
press When the mouse pointer is moved over the Hit area of the bu on
and the mouse is pressed
release When the mouse pointer is moved over the Hit area of the bu on
and the mouse is pressed and then released
releaseOutside When a press occurs on the Hit area of a bu on, and then the
mouse pointer is moved outside of the Hit area and released
rollOver When the mouse pointer moves over the Hit area of a bu on
rollOut When the mouse pointer moves off of the Hit area of a bu on
dragOver When the mouse is pressed on the Hit area of a bu on, then rolls
out of the Hit area, and reenters the Hit area with the mouse still
pressed
dragOut When the mouse is pressed on the Hit area of a bu on, and then
the mouse pointer rolls out of the Hit area with the mouse still
pressed
keyPress When the specified key is pressed on the keyboard
When you add an action to a bu on object, you must introduce an event. In this example, In this
illustration, the event is a mouse event named on (release), meaning that when the user presses
and releases the mouse bu on, the action gotoAndStop() is triggered.
To enter a mouse event, you first need to enter on ( . Once you have entered the on ( handler,
Flash’s Code Hints will give you a drop-down list of possible events you can handle.
170
INTRODUCTION TO ACTIONSCRIPT
A er you have selected the event, add a closing parenthesis. Then you’ll need to add a pair of curly
braces { } that indicate what actions should be performed when the event is triggered.
Exercise 9.2 – Adding Button Events
1. Using the Flash movie “amazon_animals.fla”, select the MainMenu scene.
2. Select the Bu on layer in frame 1 and add the following bu ons to the stage:
Jaguar Bu on
Margay Bu on
Marmoset Bu on
Quiz Bu on
When you’re finished, your main menu may look something like this:
171
INTRODUCTION TO ACTIONSCRIPT
3. Select the Jaguar Bu on and open the Actions panel. Add an on(release) handler to the
bu on. Add an opening curly brace ( { )and then add a gotoAndStop() action to the script.
There are 2 different ways that gotoAndStop() works. If you are going to go to a frame in the
same Scene, then you only need to specify the frame number or label. If you are going to go to a
frame in a different scene, then you either need to first specify the scene, then specify the frame
you are going to, or specify the frame label you are going to.
4. Inside of the parenthesis, enter “Instruction” (including the quotes) for the Scene, then
enter a comma ( , ) then enter “Jaguar” (including the quotes) for the frame. Finally, move to
the next line and enter the closing curly brace ( } ).
The completed bu on script will look like this:
on (release) {
gotoAndStop(“Introduction”, “Jaguar”);
}
5. Repeat this step for the Margay Bu on and Marmoset Bu on.
6. Add a bu on script to the Quiz Bu on that uses gotoAndStop() to take the user to frame 1 of
the Quiz scene.
7. Test the movie.
The main menu now allows us to go to the different animals in the Instruction scene and to the
Quiz scene.
To complete our movie, we now need to add some navigation bu ons to the Instruction scene
and to add a script to the Menu bu on on the Quiz scene.
8. Select the Instruction scene. Add the following bu ons to the following layers:
Previous Bu on Previous
Next Bu on Next
Menu Bu on Main Menu
Make sure that the bu ons appear in all three frames of the scene.
172
INTRODUCTION TO ACTIONSCRIPT
9. Add the following actions to the corresponding bu on in an on (release) handler:
prevFrame(); Previous Bu on
nextFrame(); Next Bu on
gotoAndStop(“MainMenu”, 1); Menu Bu on
10. Test the movie. The movie should now be complete. Save and close the movie.
173
INTRODUCTION TO ACTIONSCRIPT
WORKING WITH TEXT FIELDS
There will be times as you create an e-Learning project that you’ll need to get some kind of user
input or display some kind of text message or other information. You’ll use Dynamic Text Fields to
display information, and Input Text Fields to get information from the user.
To illustrate how we can use text fields, we’re going to create a math quiz to test multiplication skills
on numbers between 0 and 10. To do this, we’ll need to learn to use some new ActionScript actions to
create the numbers in the quiz, to check the student’s answers, and to set instance names and variable
references for our text fields.
Our quiz will function like this:
The Student clicks a bu on to ask for a question
The movie picks 2 numbers for the multiplication problem
The student enters their answer, then clicks a bu on to check their answer
The movie checks the answer and lets the student know if they are correct.
Let’s start by adding the bu ons and the text boxes for the quiz.
174
INTRODUCTION TO ACTIONSCRIPT
Exercise 9.3 – Text Fields and ActionScript
1. Open the Flash movie Chapter9/ MathBlastOff.fla.
2. Add 5 text fields to the Stage. Create them with the following properties:
Type Instance Name Variable Field content
Dynamic txtOne vOne
Static X
Dynamic txtTwo vTwo
Static =
Input txtAnswer
A er you have added the fields, your project should look something like this:
175
INTRODUCTION TO ACTIONSCRIPT
SETTING VARIABLES AND EXPRESSIONS
A variable is a container that holds information. The container itself is always the same, but the
contents can change. By changing the value of a variable as the Flash movie plays, you can record
and save information about what the user has done, record values that change as the movie plays, or
evaluate whether a condition is true or false.
Some of the types of variables you’ll be using in ActionScript include:
string A string is a sequence of characters such as le ers, numbers, and
punctuation marks. You enter strings in an ActionScript statement
by enclosing them in single (‘) or double (“) quotation marks.
number A number is any numerical value, such as integers or decimals.
You can manipulate numbers using the arithmetic operators
addition (+), subtraction (-), multiplication (*), division (/),
modulo (%), increment (++), and decrement (--).
You can also use methods of the built-in Math and Number classes
to manipulate numbers.
boolean A Boolean value is one that is either true or false. ActionScript
also converts the values true and false to 1 and 0 when
appropriate. Boolean values are most o en used with statements
that make comparisons to control the flow of a script.
Variable Scope
How and where you declare a variable determines a variable’s scope, which refers to the area in
which the variable is known and can be referenced. There are three types of variable scopes in
ActionScript:
● Global variables are visible to every Timeline and scope in your document.
● Timeline variables are available to any script on that Timeline.
● Local variables are available within the function in which they are declared (delineated by
curly braces).
176
INTRODUCTION TO ACTIONSCRIPT
Timeline variables
Timeline variables are available to any script on that Timeline. To declare Timeline variables, use the
var statement and initialize them in any frame in the Timeline; the variable will be available to that
frame and all following frames, as shown in the following example:
var x:Number = 15;
//initialized in Frame 1, so it’s available to all frames
Make sure to declare a Timeline variable before trying to access it in a script. For example, if you put
the code var x = 10; in Frame 20, a script a ached to any frame before Frame 20 cannot access that
variable.
Local variables
To declare local variables, use the var statement inside the body of a function. A local variable
declared within a function block is defined within the scope of the function block and expires at the
end of the function block. For example in the following script:
function showName(nameToShow:String) {
var newName:String;
newName = nameToShow.toUpperCase();
trace (newName);
}
showName(“David”);
trace (newName);
The output would be:
DAVID
Undefined
Because the variable is declared inside of the function, once the script leaves the function, the
variable is not defined.
177
INTRODUCTION TO ACTIONSCRIPT
Global variables
Global variables are visible to every Timeline and scope in your document. To create a variable with
global scope, use the _global identifier before the variable name and do not use the var = syntax.
For example, the following code creates the global variable g_MyName:
_global.g_MyName = “George”;
If a Timeline or local variable is declared with the same name as a global variable, it will take
precedence over the global variable. One time to keep variable names unique is to add g_ to the
beginning of a global variable.
Returning to our current project, since we have created our interface with our text fields, we’ll need
to create the scripts that will put the math problem on the screen and check the answer. We’ll do this
by creating 2 variables - vOne and vTwo - to store the numbers that will be multiplied together. We’ll
later use those variables to check the answer of the problem.
178
INTRODUCTION TO ACTIONSCRIPT
Exercise 9.4 – Using Variables
1. Select the Ready bu on and open the Actions panel.
2. Add an on (release) handler for the Ready bu on.
3. Add the following 2 lines of script to the on (release) handler on the Ready bu on
vOne = Math.round((Math.random() * 10));
vTwo = Math.round((Math.random() * 10));
In the handler, we need to select two numbers for the student to multiply. To do this, we’re
defining 2 variables, vOne and vTwo, and se ing them with our script that will pick a number
between 0 and 10. To pick the number, we’ll use the random method from the Math class (Math.
random()). The random method picks a number between 0 and 1, so to have the largest possible
number in our quiz be 10, we’ll need to multiply the value we get from the random method by
10. Finally, since we want whole numbers, we’ll use the round method (Math.round()) to round
the number to the nearest whole number.
4. Add the following line of script to the end of the handler to clear the contents of the
txtAnswer field:
txtAnswer.text = “”;
5. Test the movie.
When you click on the Ready bu on, a math problem is displayed.
6. Save the movie. We’ll continue to use this movie in the next exercise.
179
INTRODUCTION TO ACTIONSCRIPT
CONTROLLING MOVIE CLIPS
Another common task for ActionScript is to control movie clips. Since movie clips have their own
timeline, you can stop the playback of the movie clip timeline, set the current frame of the movie clip,
and much more.
For our quiz game, we’re going to add a movie clip that will show the user their progress in ge ing
answers correct.
Exercise 9.5 – Controlling Movie Clips
1. Add the Rocketman movie clip to the right side of the stage. Set the instance name of the
movie clip to mcRocketman.
The Rocketman movie clip has 10 frames that will be used to show the student their progress in
the quiz. When the student gets a question correct, we’ll move the Rocketman up the screen one
frame, if they get a question wrong, we’ll move back one frame.
2. Select the BlastOff bu on and open the Actions panel. Create an on (release) handler like
the following script:
on (release) {
if (number(txtAnswer.text) == vOne * vTwo) {
}
else {
}
}
To check if the student answered correctly, we need to use an if statement to check their answer.
We also are going to use an else statement if they get the question wrong. The way the if and
else statements work is the following:
180
INTRODUCTION TO ACTIONSCRIPT
if(condition) {
statement(s);
}
else {
statement(s);
}
In our example, we’re going to test to see if the number in the txtAnswer field is equal to variable
vOne times variable vTwo.
To test for equality, you need to use 2 equal signs (==). If you use only one equal sign (=), you are
assigning a value to a variable or object property.
3. For the statement in the if, add the following:
mcRocketman.nextFrame();
This will move the Rocketman movie clip ahead one frame.
4. For the statement in the else, add the following:
if (mcRocketman._currentFrame != 1) {
mcRocketman.prevFrame();
}
We’ve added an additional if statement to see if the current frame in our movie clip is not ( ! = ) at
frame 1. If it isn’t, we’ll have our movie clip move to the previous frame.
181
INTRODUCTION TO ACTIONSCRIPT
Once you’ve added this script, the final handler will look like this:
on (release) {
if (number(txtAnswer.text) == vOne * vTwo) {
mcRocketman.nextFrame();
}
else {
if (mcRocketman._currentFrame != 1) {
mcRocketman.prevFrame();
}
}
}
5. Test the movie. Now that we’ve added the script to check the answer, our small quiz is
complete for now. Once you’ve finished taking the quiz, save the file and close it.
182
INTRODUCTION TO ACTIONSCRIPT
CONTROLLING VIDEO WITH ACTIONSCRIPT
There may be instances where you’ll want to allow control of the playback of the video clips in your
movie. To accomplish this, we’ll need to add the video clip to a movie clip, which will allow us to
control the Timeline of the video clip while it is playing.
Exercise 9.6: Controlling Video with ActionScript
1. Create a new Flash document.
3. Choose File -> Import to Library
4. From the student files, select Chapter7 / jump.mov. Click the Open/Import bu on.
The Video Import Wizard appears, providing complete control over the entire importing process.
5. Choose the Embed option. Click the Next bu on.
6. In the dialog box that appears, choose Import the entire video. Click the Next bu on.
7. In the dialog box that appears, chose DSL/Cable 256 kbps from the Compression profile drop-
down menu and click the Finish bu on.
The video clip is added to the library
8. Create a new movie clip and name it “Jump Video”. Drag the jump.mov video clip from the
Library to the movie clip stage.
9. When Flash displays a confirmation box about the number of frames the video requires on the
Timeline, click Yes.
10. Close the Jump Video movie clip editing mode and return to the main Timeline.
11. Drag the Jump Video movie clip to the Stage. In the Property inspector, name the instance of
the movie clip mc_Jump.
183
INTRODUCTION TO ACTIONSCRIPT
12. Open the Bu ons from the Common Libraries and drag the Play, Stop, and Rewind bu ons
from the Circle Bu ons category to the Stage.
13. Select the Play bu on and open the Actions panel. Add the following script to the Play bu on:
on (release) {
mc_Jump.play();
}
14. Add a script to the Stop bu on that stops the movie clip playback (mc_Jump.stop()), and add
a script to the Rewind bu on that stops playback and rewinds to the first frame of the movie
clip (mc_Jump.gotoAndStop(1)).
15. Test the movie and close when you’re finished.
184
INTRODUCTION TO ACTIONSCRIPT
LOADING A QUIZ INTO AN EXISTING MOVIE
Because of the number of objects involved in a complete quiz, it is not recommended to try to import
a quiz into an existing movie. Rather, you should use the Flash loadMovie() action to load the quiz
into your existing Flash movie at runtime.
Once you have used the loadMovie() action to load the quiz movie, you’ll need to use loadMovie()
to reload your main movie once the user is finished with the quiz.
Exercise 9.7: Loading a Quiz
1. From the student files, open the file Chapter9 / amazonmenu.fla.
2. Click on the Quiz bu on on the Stage and open the Actions panel.
3. Enter the following script:
on(release) {
loadMovie(“amazonanimals.swf”, this);
}
The this parameter tells Flash to load the movie into the same Timeline as the bu on, which is
the main Timeline. You can also specify a movie clip to load the movie into.
4. Save and test the movie. When the quiz bu on is clicked, the Quiz will load into the existing
movie.
185