Understanding the ActionScript Language
Differences Between ActionScript and JavaScript
Deconstructing a Sample Script
Variables
Using Operators
Using Actions
Writing a Target Path
Using Built-in Functions
Creating Functions
About Built-in Objects
About Custom Objects
ActionScript allows you to create a movie that behaves exactly as you want. You do not need to understand every ActionScript element to begin scripting.
In this section of the class we will begin by creating simple actionscripts to do simple actions.
The ActionScript syntax and style closely resemble that of JavaScript. Flash MX understands ActionScript written in any previous version of Flash.
This section introduces you to ActionScript as an object-oriented scripting language and provides an overview of ActionScript terms and basic programming concepts such as functions, variables, statements, operators, conditionals, and loops.
To begin scripting with ActionScript right away, complete the ActionScript tutorial
(Help > Tutorials > Introduction to ActionScript)
Differences Between ActionScript and JavaScript
Some of the differences between ActionScript and JavaScript are as follows:
ActionScript does not support browser-specified objects such as Documents, Windows, and Anchor.
ActionScript does not completely support all of the JavaScript built-in objects.
ActionScript supports syntax constructs that are not permitted in JavaScript (for example, the tellTarget and ifFrameLoaded actions and slash syntax). However, the use of these syntax constructs is not recommended ; instead, use ActionScript elements that are like those in JavaScript (for example, with, _framesloaded, and dot syntax).
ActionScript does not support some JavaScript syntax constructs, such as try, catch, throw, and statement labels.
ActionScript does not support the JavaScript Function constructor.
In ActionScript, the eval action can only perform variable references.
In JavaScript, toString of undefined is undefined. In Flash 5 and Flash MX, for Flash 4 compatibility, toString of undefined is " ".
About Scripting in ActionScript
ActionScript is an easy-to-learn object oriented programming language. It's object oriented but you don't need to declare a class or have any knowledge on objects. You will be able to use built-in objects at the end of this tutorial. Being the first step, we will learn where to write your code in Flash.
In Flash, you can write your code 'attached' to keyframes or symbols instances . Select a keyframe or an instance of a symbol at the scene then go to the ActionScript editor. [From now on, you are an 'expert' according to the ActionScript editor and you need to use Expert Mode of the editor.] What you select [a symbol instance or a keyframe] is what your code is attached to.
A code that is attached to a keyframe is executed when that frame plays (ie the playhead passes it).
If you write your code into [I mean attached to] a keyframe, you can access the symbol instances by using their names only. Lets look at this example:
| myfirsttext.text="Helloooo Woooorld!!!"; |
We named something on the scene, we accessed it and changed a property of it. text property is a property of the textfield object; it carries the inner text of the text box.
Before looking at the second place to write the code into (ie attaching code to symbol instances instead of keyframes) lets take a closer look at objects referencing to them.
The "dot" Syntax
We used a dot (.) in our first example, between the object (myfirsttext) and it's property (text). The dot syntax is very common but I will explain it because I said you don't need to know anything about objects.
An object in a programming language is like an object in real life. Take your mouse as an example. Lets name it mymouse. Now we can access it's right_button by writing mymouse.right_button. This right button can be clicked by the "method" mymouse.right_button.click(). When we use this method, an event will occur: mymouse.right_button.onClick. Getting this idea will be enough: the leftside of the dot is the owner of the rightside of the dot.
Absolute ReferencingIn ActionScript, the master owner of everything in a movie is _root. If you create a symbol instance on the scene, and name it theobject, you can access it from anywhere in the movie typing _root.theobject. If you have the symbol instance (myinstance) on the scene at level 0 (it means the symbol is owned by directly the movie not by another symbol) and in that symbol, you have another (mychildinstance), you can call it _root.myinstance.mychildinstance This is an absolute reference for the object that works from everywhere in the movie.
Relative ReferencingIf we want to attach code to a keyframe of mychildinstance object, we can access myinstance object with the keyword: _parent. This keyword makes possible for us to access the owner of where this code is written. We can access another object on the scene named myfirsttext from mychildinstance by using _root.myfirsttext or _parent._parent.myfirsttext. The first _parent is myinstance and the second one means the parent of myinstance, ie _root. You should understand this very well in order to avoid first-step-errors writing your ActionScript code.
"this" Keywordthis keyword is used to reference the object's itself. For now, it is enough to learn this. We will use it in function implementations but you don't need to worry about it now.
Coding into Symbol Instances
You can also write code attached to symbol instances. The code attached to instances consists of event handlers for that symbol instance. If symbol is a button, the instance will be a button object and if it is a movie clip the instance will be a movieClip object. You can use on(name_of_the_event) or onClipEvent(name_of_the_event) event handlers. For example, create a rectangle on the stage and convert it into a movie clip symbol by pressing F8. Select it and write this code into the editor:
| on (rollOver) { trace("I am an ActionScript expert"); } |
Control>>Test Movie and move your mouse over the rectangle. You will see our message in the output window. When you type on ( and wait, a scrollable box will appear that contains the available event names. You may chose from the list or also write it by hand. The code between { } braces will be executed when the event occurs. trace() is a builtin ActionScript function which doesn't have any meanings for the final product. It is used only when authoring to see what the code is doing to find out errors. rollOver is the name of the event when occurs you move your mouse over the object.
The difference between on() and onClipEvent() is the types of the events they handles. on() is for button events. I didn't say for button's, be careful; you can use them also with movieClip objects. These events are standart events for buttons, like onRollOver or onRelease (occurs when you click the instance).
Movie clip events are used for only with movieClip objects. For example, one of them is load which occurs when a movie clip loads (ie it is downloaded completely)
Lastly, summary of what we have learned from this tutorial:
ActionScript has rules of grammar and punctuation that determine which characters and words are used to create meaning and in which order they can be written. For example, in English, a period ends a sentence. In ActionScript, a semicolon ends a statement.
The following general rules apply to all ActionScript. Most ActionScript terms also have their own individual requirements; for the rules for a specific term, see its entry in the online ActionScript Dictionary in the Help menu.
Dot syntax
In ActionScript, a dot (.) is used to indicate the properties or
methods related to an object or movie clip. It is also used to identify the
target path to a movie clip, variable, function, or object. A dot syntax
expression begins with the name of the object or movie clip followed by a dot,
and ends with the element you want to specify.
For example, the _x movie clip property indicates a movie clip's
x axis position on the Stage. The expression ballMC._x refers to
the _x property of the movie clip instance ballMC.
As another example, submit is a variable set in the form
movie clip, which is nested inside the movie clip shoppingCart. The
expression shoppingCart.form.submit = true sets the submit
variable of the instance form to true.
Expressing a method of an object or movie clip follows the same pattern. For
example, the play method of the ballMC instance moves
the playhead in the Timeline of ballMC, as in the following
statement:
ballMC.play();
Dot syntax also uses two special aliases, _root and
_parent. The alias _root refers to the main Timeline. You
can use the _root alias to create an absolute target path. For
example, the following statement calls the function buildGameBoard
in the movie clip functions on the main Timeline:
_root.functions.buildGameBoard();
You can use the alias _parent to refer to a movie clip in which
the current movie clip is nested. You can also use _parent to
create a relative target path. For example, if the movie clip dog
is nested inside the movie clip animal, the following statement on
the instance dog tells animal to stop:
_parent.stop();
Curly braces
ActionScript statements are grouped together into blocks with curly braces ({
}), as in the following script:
on(release) {
myDate = new Date();
currentMonth = myDate.getMonth();
}
Semicolons
An ActionScript statement is terminated with a semicolon. For example, the following statements are terminated with semicolons:
column = passedDate.getDay(); row = 0;
If you omit the terminating semicolon, Flash will still compile your script successfully. However, using semicolons is good scripting practice.
Parentheses
When you define a function, place any parameters inside parentheses:
function myFunction (name, age, reader){... }
When you call a function, include any parameters passed to the function in parentheses, as shown here:
myFunction ("Steve", 10, true);
You can also use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read. (See Operator precedence.)
You also use parentheses to evaluate an expression on the left side of a dot
in dot syntax. For example, in the following statement, the parentheses cause
new Color(this) to evaluate and create a new Color object:
onClipEvent(enterFrame) {
(new Color(this)).setRGB(0xffffff);
}
If you didn't use parentheses, you would need to add a statement to evaluate the expression:
onClipEvent(enterFrame) {
myColor = new Color(this);
myColor.setRGB(0xffffff);
}
Uppercase and lowercase letters
Only keywords in ActionScript are case sensitive; with the rest of ActionScript, you can use uppercase and lowercase letters interchangeably. For example, the following statements are equivalent:
cat.hilite = true; CAT.hilite = true;
However, it's good practice to follow consistent capitalization conventions, such as those used in this manual, to make it is easier to identify names of functions and variables when reading ActionScript code.
Because ActionScript is not case sensitive, you must not use variable names that match built-in ActionScript objects. For example, the following is not allowed:
date = new Date();
Instead, use the variable names myDate, theDate,
and so on.
If you don't use correct capitalization with keywords, your script will have errors. When Colored Syntax is turned on in the Actions panel, keywords written with correct capitalization are blue by default.
Comments
In the Actions panel, use comments to add notes to scripts. Comments are useful for keeping track of what you intended, and for passing information to other developers if you work in a collaborative environment or are providing samples.
When you choose the comment action, the characters //
are inserted into the script. Even a simple script is easier to understand if
you make notes as you create it:
on(release) {
// create new Date object
myDate = new Date();
currentMonth = myDate.getMonth();
// convert month number to month name
monthName = calcMonth(currentMonth);
year = myDate.getFullYear();
currentDate = myDate.getDate();
}
When Colored Syntax is turned on in the Actions panel, comments are pink by default in the Script pane. Comments can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords
Keywords
ActionScript reserves words for specific use within the language, so you can't use them as variable, function, or label names. The following table lists all ActionScript keywords:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For more information about a specific keyword, see its entry in the online ActionScript Dictionary in the Help menu.
Constants
A constant is a property whose value never changes.
For example, the constants BACKSPACE, ENTER,
QUOTE, RETURN, SPACE, and TAB are
properties of the Key object and refer to keyboard keys. To test whether the
user is pressing the Enter key, you could use the following statement:
if(Key.getCode() == Key.ENTER) {
alert = "Are you ready to play?";
controlMC.gotoAndStop(5);
}
A data type describes the kind of information a variable or ActionScript element can hold. There are two kinds of data types: primitive and reference. The primitive data types—string, number, and boolean—have a constant value and therefore can hold the actual value of the element they represent. The reference data types—movie clip and object—have values that can change and therefore contain references to the actual value of the element. Variables containing primitive data types behave differently in certain situations than those containing reference types. There are also two special data types: null and undefined.
Each data type has its own rules and is described in the following topics:
|
|
String A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single or double quotation marks. Strings are treated as characters instead of as variables. For example, in the following statement, "L7"
is a string:
favoriteBand = "L7"; You can use the addition (+ greeting = "Welcome," + firstName; Although ActionScript does not distinguish
between uppercase and lowercase in references to variables, instance
names, and frame labels, literal strings are case sensitive. For
example, the following two statements place different text in the
specified text field variables, because invoice.display = "Hello"; invoice.display = "HELLO"; To include a quotation mark in a string, precede it with a backslash character (\). This is called "escaping" a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table provides all the ActionScript escape characters:
|
||||||||||||||||||||||||
|
|
Number The number data type is a double-precision
floating-point number. You can manipulate numbers using the arithmetic
operators addition ( Math.sqrt(100);
|
||||||||||||||||||||||||
|
|
Boolean A Boolean value is one that is either true or false. ActionScript
also converts the values onClipEvent(enterFrame) {
if (userName == true && password == true){
play();
}
}
|
||||||||||||||||||||||||
|
|
Object An object is a collection of properties. Each property has a name and
a value. The value of a property can be any Flash data type, even the
object data type. This allows you to arrange objects inside each other,
or "nest" them. To specify objects and their properties, you use the dot
( employee.weeklyStats.hoursWorked You can use the built-in ActionScript objects to
access and manipulate specific kinds of information. For example, the
Math object has methods that perform mathematical operations on numbers
you pass to them. This example uses the squareRoot = Math.sqrt(100); The ActionScript MovieClip object has methods
that let you control movie clip symbol instances on the Stage. This
example uses the mcInstanceName.play(); mc2InstanceName.nextFrame(); You can also create your own objects to organize information in your movie. To add interactivity to a movie with ActionScript, you'll need many different pieces of information: for example, you might need a user's name, the speed of a ball, the names of items in a shopping cart, the number of frames loaded, the user's zip code, or the key that was pressed last. Creating custom objects allows you to organize this information into groups, simplify your scripting, and reuse your scripts. |
||||||||||||||||||||||||
|
|
Movieclip Movie clips are symbols that can play animation in a Flash movie.
They are the only data type that refers to a graphic element. The
movieclip data type allows you to control movie clip symbols using the
methods of the MovieClip object. You call the methods using the dot ( myClip.startDrag(true);
parentClip.getURL("http://www.macromedia.com/support/" + product);
|
||||||||||||||||||||||||
|
|
Null The null data type has only one value,
|
||||||||||||||||||||||||
|
|
Undefined The undefined data type has one value,
|
About Planning and Debugging Scripts
About Object-Oriented Scripting
Controlling When ActionScript Runs
Like any scripting language, ActionScript uses its own terminology. The following list provides an introduction to important ActionScript terms in alphabetical order.
Actions are statements that instruct a movie to do something while it
is playing. For example, gotoAndStop sends the playhead to a
specific frame or label. In this manual, the terms action and statement are
interchangeable.
Boolean is a true or false value.
Classes are data types that you can create to define a new type of object. To define a class, you create a constructor function.
Constants are elements that don't change. For example, the constant
Key.TAB always has the same meaning: it indicates the Tab key on a
keyboard. Constants are useful for comparing values.
Constructors are functions that you use to define the properties and
methods of a class. For example, the following code creates a new Circle class
by creating a constructor function called Circle:
function Circle(x, y, radius){
this.x = x;
this.y = y;
this.radius = radius;
}
Data types are a sets of values and the operations that can be performed on them. The ActionScript data types are string, number, boolean, object, movieclip, function, null, and undefined. For more details on these language elements, see About data types.
Events are actions that occur while a movie is playing. For example, different events are generated when a movie clip loads, the playhead enters a frame, the user clicks a button or movie clip, or the user types at the keyboard.
Event handlers are special actions that manage events such as
mouseDown or load. There are two kinds of ActionScript event
handlers: actions and methods. There are only two event handler actions,
on and onClipEvent. In the Actions toolbox, each
ActionScript object that has event handler methods has a subcategory called
Events.
Expressions are any legal combination of ActionScript symbols that
represent a value. An expression consists of operators and operands. For
example, in the expression x + 2, x and 2
are operands and + is an operator.
Functions are blocks of reusable code that can be passed parameters
and can return a value. For example, the getProperty function is
passed the name of a property and the instance name of a movie clip, and it
returns the value of the property. The getVersion function returns
the version of the Flash Player currently playing the movie.
Identifiers are names used to indicate a variable, property, object,
function, or method. The first character must be a letter, underscore (_),
or dollar sign ($). Each subsequent character must be a letter,
number, underscore, or dollar sign. For example, firstName is the
name of a variable.
Instances are objects that belong to a certain class. Each instance of
a class contains all the properties and methods of that class. All movie clips
are instances with properties (for example, _alpha and
_visible) and methods (for example, gotoAndPlay and
getURL) of the MovieClip class.
Instance names are unique names that allow you to target movie clip
and button instances in scripts. You use the Property inspector to assign
instance names to instances on the Stage. For example, a master symbol in the
library could be called counter and the two instances of that
symbol in the movie could have the instance names scorePlayer1 and
scorePlayer2. The following code sets a variable called score
inside each movie clip instance by using instance names:
_root.scorePlayer1.score += 1; _root.scorePlayer2.score -= 1;
Keywords are reserved words that have special meaning. For example,
var is a keyword used to declare local variables. You cannot use a
keyword as an identifier. For example, var is not a legal variable
name.
Methods are functions assigned to an object. After a function is
assigned, it can be called as a method of that object. For example, in the
following code, clear becomes a method of the controller
object:
function reset(){
this.x_pos = 0;
this.x_pos = 0;
}
controller.clear = reset;
controller.clear();
Objects are collections of properties and methods; each object has its own name and is an instance of a particular class. Built-in objects are predefined in the ActionScript language. For example, the built-in Date object provides information from the system clock.
Operators are terms that calculate a new value from one or more
values. For example, the addition (+) operator adds two or more
values together to produce a new value. The values that operators manipulate are
called operands.
Parameters (also called arguments) are
placeholders that let you pass values to functions. For example, the following
welcome function uses two values it receives in the parameters
firstName and hobby:
function welcome(firstName, hobby) {
welcomeText = "Hello, " + firstName + "I see you enjoy " + hobby;
}
Properties are attributes that define an object. For example,
_visible is a property of all movie clips that defines whether a movie
clip is visible or hidden.
Target paths are hierarchical addresses of movie clip instance names,
variables, and objects in a movie. You name a movie clip instance in the movie
clip Property inspector. (The main Timeline always has the name _root.)
You can use a target path to direct an action at a movie clip or to get or set
the value of a variable. For example, the following statement is the target path
to the variable volume inside the movie clip stereoControl:
_root.stereoControl.volume
Variables are identifiers that hold values of any data type. Variables can be created, changed, and updated. The values they store can be retrieved for use in scripts. In the following example, the identifiers on the left side of the equal signs are variables:
x = 5; name = "Lolo"; customer.address = "66 7th Street"; c = new Color(mcinstanceName);
Deconstructing a Sample Script
In the sample movie zapper.swf, when a user drags the bug to the electrical outlet the bug falls and the outlet shakes. The main Timeline has only one frame and contains three objects: the ladybug, the outlet, and a reset button.Each of these objects is a movie clip instance.
There is one script in the movie; it's attached to the bug
instance, as in the Actions panel below:
The Actions panel with the script attached to the
bug instance
The bug's instance name is bug and the outlet's instance name is
zapper. In the script the bug is referred to as this
because the script is attached to the bug and the reserved word this
refers to the object that contains it.
There are two onClipEvent handlers with two different events:
load and enterFrame. The actions in the
onClipEvent(load) statement execute only once, when the movie loads. The
actions in the onClipEvent(enterFrame) statement execute every time
the playhead enters a frame. Even in a one-frame movie, the playhead still
enters that frame repeatedly and the script executes repeatedly. The following
actions occur within each onClipEvent handler:
onClipEvent(load) Two variables, initx and inity,
are defined to store the inital x and y positions of the bug movie
clip instance. A function is defined and assigned to the onRelease
event of the Reset instance. This function is called each time the mouse is
pressed and released on the Reset button. The function places the ladybug back
in its starting position on the Stage, resets its rotation and alpha values, and
resets the zapped variable to false.
onClipEvent(enterFrame) A conditional if statement uses
the hitTest method to check whether the bug instance is touching
the outlet instance (_root.zapper). There are two possible outcomes
of the evaluation, true or false:
onClipEvent (load) {
initx = _x;
inity = _y;
_root.Reset.onRelease = function() {
zapped = false;
_x = initx;
_y = inity;
_alpha = 100
_rotation = 0;
};
}
If the hitTest method returns true, the
stopDrag method is called, the zapper variable is set to
true, the alpha and rotation properties are changed, and the
zapped instance is told to play.
If the hitTest method returns false, none of the
code within the {} immediately following the if
statement runs.
There are two on handlers attached to the bug
isntance with two different events: press and release.
The actions in the on(press) statement execute when the mouse is
pressed over the bug instance. The actions in the on(release)
statement execute when the mouse is released over the bug instance.
The following actions occur within each onClipEvent handler:
on(press) A startDrag action makes the ladybug draggable.
Because the script is attached to the bug instance, the keyword
this indicates that it is the bug instance that is
draggable:
on (press) {
this.startDrag();
}
on(release) A stopDrag action stops the drag action:
on (release) {
stopDrag();
}