To shape tween grouped shapes, break them apart and tween each one.
Every action has a controlling script.
Scripts used to add actions on buttons must always be placed in an event handler, which specifies the conditions under which the action is executed.
see Movie Clips
Events trigger actions, actions are performed by using event handlers. You must define and event handler for an event to perform a specified task. There are two types of event handlers:
By default Flash event handlers are not pre-defined and your application will not respond to events you create. To define an event handler:
An event handler has three parts:
Two methods for handling events:
Objects that receive events from an object and performs the actions given in the function. You can attach multiple listener objects to receive events from a single object or a single listener object to receive events from multiple objects. You must first inform the object that triggers the event to inform the object holding the listening event handler that an event is triggered. Use the addListener() method.
You can access the variables used in event handler functions outside the event handler because when you attach the event handler directly to an object, such as a button, the variables have a Timeline scope and can be used anywhere across the Timeline. So, different objects placed across the Timeline can refer to a common variable. However, when you call an event handler method attached to an object, such as a movie clip, the variables have the function scope and can be used only in the function where it is declared.
There are two types of event handler that you attach to objects, on() and onClipEvent():
Used with buttons and movie clips
on(rollOver) {
_width+ = 150;
}
on(rollOut) {
_width- = 150;
}
For movie clip events only. For example: executing code when a movie loads or unloads, or when you enter a movie frame. onClipEvent() provides additional events such as enterFrame, not provided by on().
onClipEvent(enterFrame) {
_rotation+ = 10
}
You can also handle (respond to) events by using event handler methods, such as the onPress method that is invoked whenever the mouse is pressed on a movie clip object. Event handler methods are not directly attached to objects, but are assigned to objects (i.e., the code is attached to the frame which contains the object).
For example, this code is triggered when the object is selected and it changes the transparency of the object. Obj is the name of the object to which the onPress event handler method is attached with a dot operator. The function() keyword is necessary for the code within the braces {} to execute.
Obj.onPress = function() {
Obj._alpha = 30
}
All words used in ActionScript are case sensitive.
Dot is an operator that you use to call the property or method of an object or a movie clip.
For example, if you want the user to press myButton to perform an action, specify the onPress method for the button. Use the syntax: myButton.onPress
myButton.onPress = function() {
ball._xscale = 200;
ball._yscale = 200;
}
You can also use the dot operator to refer to and call the methods and properties of nested objects that are objects created within other objects. First specify the entire path where the object is located using the dot operator. For example, to call the propery visible for a button named myButton in a form named myForm:
myForm.myButton.visible = True;
myButton.onPress = function() {
ball._xscale = 200;
ball._yscale = 200;
}
Use braces to group multiple lines of script together as a single block, making it easier to read and understand. Each opening brace { must have a corresponding closing brace }. Use braces with loop statements that are used to repeat script or functions used to name the grouped script. Also use braces with conditional statements. Braces can also be nested.
{
if (loginname!="Debbie")
{
messg="Username not found.";
} else
{
gotoAndStop(2);
}
}
A Semicolon is used to indicate the end of a line in the script. Technically, the Flash Player compiles and executes the script without the ;, but it's good programming practice to use it.
Parentheses are mainly used with a function to enclose the parameters (values) passed to the function. For instance, to calculate the area of a circle, the function will require the radius of the circle, which is passed to the function using ().
public function getVolume (radius:Number) :Number {
return 22/7*radius*radius
}
Use parentheses to group and prioritize operations, including nesting. d = (a+b)/c;
Use parentheses with functions and properties. For example, to evaluate an expresson on the left side of the dot operator. Then apply the necessary operations on the object on the right of the dot operator. Here, Color is a function to which the object this is passed as a parameter. setRGB (0xfffffff) is a property that will be applied to the object this defined in the function Color.
onClipEvent(enterFrame) {
(new Color(this)).setRGB(0xffffff);
}
Comments are used to add explanation about the script and will not
compile. Begin a single line comment with //
Begin multi-line comments with /* enter comment and end with */.
Example:
/* the following statements will display
The volume of the two balls.
The volume will be displayed in the output window.
*/
For testing purposes, you may comment out one or more lines of code.
Keywords are predefined words that have special meanings in ActionScript. They appear in blue in the script. They cannot be used for variables or user-defined function names. Keywords include:
break
case
continue
default
delete
else
for
function
if
in
instanceof
new
return
switch
this
typeof
var
void
while
with
Constants have fixed values that do not change throughout the program. When you declare a constant, you need to assign a value to it. All letters in the name of a constant should be in uppercase. This is to distinguish the constant from other varible names. ActionScript also used constants to refer to the different keyboard actions, like:
LEFT
RIGHT
HOME
END
SPACE
ENTER
There are also constants which can be used in mathematical operations, such as:
SIN
COS
TAN
SQRT
ABS
Store scripts external to the current .fla file for re-usability.
You can add actions by using shortcut keys. To view the shortcuts in the Actions Toolbox (upper left), select View Esc Shortcut Keys in the Pop-up menu (upper right corner).
Use the = operator.
loginname = "Ed Young";
Flash uses "strict typing", if the data type does not support the data entered, it will not be stored and you get a compile error. With Automatic Data Typing, if you assign a value to an undeclared variable, Flash will create the varible for you.
You can change the data stored in a variable. You can retrieve a value stored in a variable for performing various operations, such as logical and mathematical. You can also assign the value stored in one varible to another variable. Using the varible name retrieves the data stored in it. For example:
trace ("Hi " + loginname);
The scope of the varible is the area of the application where the varible is valid. The different variable scopes in ActionScript are local, timeline, and global.
Use variables only in the function in which they are declared. For example, if you declare the variable loginname in a function emptyfields, the variable loginname will be accible only to the objects located in the function emptyfields.
function emptyfields()
{
var loginname:String;
}
The varible is accessible to all the objects on a Timeline.
The variable will be accessible to all the objects on the Timeline of the current frame and frames after the current frame. To access a Timeline variable, use the code _root.variablename
var loginname:String;
loginname - "guest";
function empty()
{
trace (_root.loginname);
}
Global variables are accessible to objects in the movie. Use the code _global.variblename = value;. After you declare the variable, you can specify the variable name to access the variable.
_global.loginname = "guest";
trace (loginname);
An array is a collection of variables that have the same variable name. You can work with all the array items together. Arrays provide an efficeint way to organize and access data. You and use an array to store and manipulate data (i.e., strings, numbers, and Boolean values). There are ActionScript methods that allow you to add, modify, and delete data from an array.
In the Actions panel, first declare the array: arrayname=new Array(); followed by the number of values to be created in the parentheses. You refer to each value as an array element. Starting with 0, each element in the array has an index number so that you can access them. Element format: arrayname[index] = "item_value";
loginname=new Array();
loginname[0] = "Debbie";
loginname[1] = "Tom";
loginname[2] = "Ken";
loginname[3] = "Larry";
loginname[4] = "Ed";
You can also assign values in the declaration statement:
loginname=new Array ("Debbie","Tom","Ken","Larry","Ed");
After creating and storing values in an array, you can access the array elements by specifying the array name and the index number.
trace ("The third element in the array : " + loginname[2]);
To size an array, use the length method:
trace ("The size of the Array : " + loginname.length);
For the above example, loginname.length will return 5. You can specify the size of an array in the declaration, but it is not recommended.
The push method adds and the pop method removes the element at the end of an array. In our example, you would add a sixth element to the end of the array:
loginname.push("Lee");
To remove the last element, in this case removing the sixth element, use pop:
loginname.pop(); //The array now has five elements
The unshift method adds and the shift method removes the element at the start of an array. In our example, a new sixth element is added as the first element of the array:
loginname.unshift("Lee");
and removed:
loginname.shift();
The splice method allow you to add and remove elements located at a specific location in the array: arrayname.splice(index_position_to_add,number_of_elements_to_delete,value_of_added_element);
To add an element:
loginname.splice(2,0,"Jim");
To remove an element:
loginname.splice(2,1);
Warning! If you do not specify the number of elements to be deleted, all the elements will be removed from the array.
The reverse method inverts the elements in an array (i.e., the first becomes the last, etc.):
loginname.reverse();
The sort method sort the elements alphabetically. Numerical values are sorted as strings:
loginname.sort();
The join method converts an array to a string. You must specify a separator to separate the array elements or the default separator will be applied (a comma followed by a space). To print the array elements separated by an colon:
trace(loginname.join(:));
The toString method also converts the array to a string with a comma as a separator, so you don't have to specify one:
loginname.toString());
Operators specify how to combine, compare, and modify values in your script. Operators are used inside expressions. An expression is a statement that ActionScript can evaluate and then return a value. The expression below has two operators, + and >=. Whereas, date, 3, and 30 are called operands. Operators specify how to perform specific operations on operands.
if (date+3 >= 30) {
}
Simple expressions, like the one above, have a single process. Complex expressions have more than one process:
if (date+3 >= 30) {
trace ("you are too old");
}
An operator working on just one operand is call a unary operator. If it is working on two operands, it is a binary operator, and when it is working on three operands, it is called a tertiary operator:
ActionScript has precise rules for determining which operator to
evaluate (i.e., precedence). For instance, multiplication before
addition, items in parenthesis always take precedence. If two operators
have the same precedence, their associativity defines their precedence.
For example, multiply left to right:
total = 2*3*4 = 6*4 not 2*12, although they all equal 24. Below is a
table of operator associativity:
(<, >, <=, >=) compare values of expressions and return a value of true or false, i.e., Boolean. Can be used in loop and conditional statements.
Use + to concatenate strings. Use comparison operators to determinse alphabetical order or to return Boolean values (i.e., checking passwords).
Logical AND (&&), logical OR (||), and logical NOT (!) compare Boolean vlaues and return a third Boolean value.
You can use logical operators to determine conditional statements.
Bitwise operators optimize computing performance (memory space) by
individually manipulating and evaluating each bit of a 32 bit intiger.
Bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~),
shift left (<<), shift right (>>), shift right zero fill
(>>>).
Assign a value to a variable. Examples:
Evaluates and returns a Boolean value
Evaluates and returns a Boolean value
Used to access properties of objects, dot (.), array access ([])
year.month="June"
arrayname [index]="Debbie"
There are three types of text fields in Flash:
Example: Create a form to allow only registered users access to a web site. Verify username and password.
res_btn.onPress = function() {
user.text=""; pass.text=""; msg.text="";
}
sub_btn.onPress = function() {
if (user.text=="Debbie" && pass.text=="Howe")
msg.text = "Access Granted"
else
msg.text = "Access Denied"
}
Stores numeric values. You can use numeric operators with these varibles. Also, the methods from Math classes can be used with the data stored in them.
var Num1:Number;
var Num2:Number;
var Total:Number;
Num1 = 10;
Num2 = 20;
Total = Num1+NUm2;
trace (Total);
Stores letters, special characters, punctuation marks, and numeric values. Enclose the data assigned to the string in quotes. Numeric values enclosed in quotes cannot be used in mathematical operations.
var Str1:String;
var Str2:String;
var Message:String;
Str1="Good";
Str2="Morning";
Message=Str1+Str2; //an example of concatenation
trace (Message);
Stores true or false values. Boolean data type can store only one value, True or False (or 1 or 0). Can be used to check for and repeat statements in conditional and loop statements.
var mycheck:Boolean;
mycheck=true;
Keeps a variable empty or indicate that the variable is not initialized or does not contain a value. You can also specify the Null value to omit the values that are supplied to a function.
var a:Number;
trace ("This will print a null value: " + a);
a=45;
trace("This will print a value of a: " + a);
function MyMethod() {
trace("A null value supplied to a function");
}
Sometimes the data type of a variable will be undefined. This happens when you do not assign a value to the variable. For example, the statement
var myvar:String;
assigns the data type undefined to myvar.
Stores a reference of a graphical element, like a movie clip symbol. This data type enables you to manage movie clips using methods from the MovieClip class. For instance, you can create and load a movie clip or control the appearance of a movie clip.
var myMovie:MovieClip=new MovieClip();
myMovie.suplicateMovieClip("newMovie",2);
myMovie.play();
This data type can organize and store customized data. You can store the data as a value to a property and assign it a name for accessing the property value. You can then group the properties in an object. For example, you can store the different features, such as the color, the size, and the position of a login screen in an object. You can then retrieve the values stored in this object and apply them to the screen before displaying it.
var inDialogStyles:Object = {
color : 0x2B333C
,width : 250
,height : 50
,x_coord : 200
,y_coord : 100
}
You can assign a value to a varible in two ways:
You can use the typeof operator to check the data type of the variable
var loginname:String;
loginname = "Ted";
trace(typeof(loginname));
A function is a set of code that can be reused by just writing one line of code. You can define a function and pass several parameters to it. However, your function will return a single value. A function must have a unique name followed by ().
function functionName (parameter1, parameter2)
{
//function body
return varName;
}
Example: Creating a mathematical computational function. Your screen has two Input Text fields for user input, one Dynamic Text field for displaying a result, and one button labeled Total to run the function.
function sum() {
var total:Number;
total = a + b;
}
To make the function global, use instead
function _global.sum()
The Actions panel provides a built-in library of global functions to select from.
Parameters are variables that store values. A function takes the parameters and executes it code on the values stored in them. You specifiy the parameters within the (), spearating them with commas.
function sum(a:Number, b:Number) {
var total:Number;
total = a + b;
}
The above parameters that are passed to the function are considered local, existing only when the function is called. Global variables can be called from any Timeline.
On execution, all functions return a value or a return statement. The function below contains a return statement. When the function is executed, it returns the value of the variable total.
function sum(a:Number, b:Number) :Number {
var total:Number;
total = a + b;
return total;
}
If you do not specify a return statement in the function, specify the return type as void. However, if you do specify a return statement, specify the return type. In the above example, the return type is specified as a Number (i.e., :Number), and returns the value of total as a number.
Every function is attached to the Timeline of a movie that defines it. Global functions are available to all Timelines if you specify the target path. The example below shows the function is called and assigned to the dynamic text field having the instance name ans. The values of the two input text fields with instance name no1 and no2 are added and returned through the variable total. You want to retun the value when you select the Total button. Therefore, in the code, the onPress event is specified on the Total button having the instance name btn.
btn.onPress = function() {
ans.text=sum(Number(no1.text), Number(no2.text));
}
function sum(a:Number, b:Number) :Number {
var total:Number;
total = a + b;
return total;
}
Key points:
Loop statements allow you to perform repreated actions without writing numerous conditional statements. Loop statements consists a series of statements that are to be repeated until the condition is true. Types of loop statements: while, do while, for, and for..in.
In Flash, when a loop statement executes, the stage contents are not updated. Moreover, when a loop is in progress, mouse events are not captured. Therefore, most Flash actions are not executed within a loop.
In the Actions panel access Add (+) \ Statements \ Conditions/Loops
while statements contain a condition and the statements to be executed. the statement can also contain a counter variable that is updated while the loop is executed. Use while statements to execute a set of statements continually untill a condition is true. However, if the condition is false, the set of statements is never exectued. In the example below, the while statement checks for the condition that variable i hsould be less than or equal to 10. If this condition is true, movie1 will play in a loop. If the value of the variable i becomes 11, the loop will end. However, if the condition is false, the loop will not be executed at all.
var i = 1;
while (i <= 10) {
movie1.play();
i++;
}
do while statements execute the code first and then check the condition. Therefore, the set of statements are executed at least once. The loop continues as long as the condition is true. However, if the condition is false, the loop will not continue further. In the example below, movie1 will play once and then the condition that variable i should be less than or equal to 10 is checked. If the condition is true, the loop continues until the value of the variable i is 11. However, if the condition is false, the loop will not continue further.
var i = 1;10);
do {
movie1.play();
i++;
} while (i <=
In the for statement, first the variable is initialized. Next, the look condition is checked. Finally, an increment (++) or decrement (--) operator is used with the variable. The for looop stops when the condition becomes false. This is the format of a for statement:
for (init; condition; next) {
statements(s);
}
In the example below, the word hello is printed 10 times. First, initialize the variable i as one. Then, specify the condition that i should be less than or equal to 10. If the condition is true, the loop is executed. The variable i is increased by one each time the word "hello" is printed. This loop ends when the condition is false.
for (var i=1; i<=10; i++) {
trace ("hello" + i):
}
for..in loops do not have a condition. Here you first define a variable and at every occurence of this variable, the actions within the for..in loop are executed. The for..in loop can only be used with objects and arrays. This is the format of a for..in loop:
for (variableIterant in object) {
statement(s);
}
For instance, you can use this to retrieve information from a database stored in an array. In this example, the database is placed in an array called arrayObject and the elements of the array are printed using the for..in loop.
arrayObject = (name: 'debbiehowe', job:'Manager', city:'New York', age:'25');
for (name in arrayObject) {
trace ("arrayObject." + name + "=" + arrayObject [name]);
}
You must always terminate a loop or it will run without stopping.
In the example below, the break statement terminates the while loop when the value of the variable i is greater than 10.
i = 0:
while (true) {
trace ("Hello");
if (i>=10)
{
break:
}
i++;
}
The continue statement enable you to interrupt the current loop iteration and restart a new loop. In the example below, the while loop prints the word Hello 10 times skipping the word World, which appears after the continue statement.
i = 0;
while (i<=10) {
i++;
trace ("Hello");
continue;
trace ("World");
}
Conditional statements enable branched or non-linear processes. You can check different conditions and write different pieces of code to speicfy the action to be taken for each condition. Types of conditional statements are: if, else, else if, switch.
Evaluates the condition to be true of false. If true, the action is executed. If false, it ignores th action and moves on to the next condition or action. A common use is for writing scrips for verification user names and passwords. In the example below, if the username matches, the application goes to the second frame and stops.
if (username == "Debbie"){
gotoAndStop(2);
}
Use an else statement if the condition is false. In the example, if the username is does not match, skip the first action and execute the else action (display the message.)
if (username == "Debbie"){
gotoAndStop(2);
}
else
{
messg="Username not found. Please try again.";
}
else if allows checking more than one condition an speicfies different action for each condition. Also, if both the if and else if conditions are false, then the else condition is eecuted. In the example, if the username is neither Debbie nor Ken, the message is displayed.
if (username == "Debbie"){
gotoAndStop(2);
}
else if (username == "Ken")
{
gotoAndStop(3);
}
else
{
messg="Username not found. Please try again.";
}
Use switch statements when a large number of conditions exist. switch statements contain a switch expression parameter, a case clause, and a default clause. The switch expression parameter uses the strict equality operator ==. The case clause uses the keyword case with an expression, a colon, and a group of actions to be executed if the expression matches. The default clause uses the keyword default with the actions to be executed of none of the case expression match. The example checks the location of the user.
switch (name) { //where is the == operator?
case "debbie":
trace("New York");
break;
case "debbiehowe":
trace("San Francisco");
break;
case "Patty":
trace("San Francisco:)'
break;
default:
trace("Not an Employee");
}
In ActionScript, target paths enable you to call movies from different timelines. Paths may be relative or absolute.
When a frame on a Timeline calls a movie residing on a separate Timeline, the calling Timeline that contains the action is called the "controlling Timeline." The Timeline that receives the action and is called to play is referred to as the "target Timeline."
An absolute path is always the full path starting from the level name and ending with the instance name. This stays the same no matter which Timeline calls the action. A relative path changes according to its location. Also, the relative path is independent of the instance name.
Absolute Path example:
_level 0.Movie 1.Movie 2
Relative Path example:
_root._parent.Movie 2
First, select the action that requires a target path (Global Funcitons/Movie Clip Control/onClipEvent)
onClipEvent () {
}
the target path of the movie to be called is always placed within the ().
Using the Insert Target Path Button: Click the crosshairs button, the Insert Target Path db displays. Click the movie clip you want to call. Select the Relative or Absolute button
Or enter the path manually:
onClipEvent () {
to = this._parent.y;
easing = 5;
}
Or create an expression that evaluates to a Target Path in a parameter box.
onClipEvent (load) {
to = this._parent.y;
easing = 5;
}
onClipEvent (enterFrame) {
this._x += (to-this._x).easing;
this._parent.ball._x+y
}
Use ActionScript to move a movie clip from its original location, scale its size, or rotate it (change angle). The advantage over full-length tweening is that it uses less memory and reduces file size. Therefore the files load faster over the Internet.
Use x, y coordinates to position an instance of a movie clip.
The example increases the x coordinate by 30 pixels, using instance name "rect" every time you click on the instance.
rect.onPress = function() {
rect._x += 30;
}
The example increases the width and height by 200 pixels. _xscale specify the width to be increased. _yscale, the height. The operator -= may be used to decrease the size.
rect.onPress = function() {
rect._xscale += 200;
rect._yscale += 200;
}
The property _rotation is used to rotate, or control the angle at which the object is displayed. The value of the property is determined from the center of the object. =+ rotates clockwise. Do not rotate circles because Flash is vector-based.
rect.onPress = function() {
rect._rotation += 10;
}
Use ActionScript to start, stop, rewind and play a movie clip frame by frame. Specify the the level at which you want to create the movie. For instance, type _root to create it at the present level, followed by accessing global function createEmptyMovieClip (+ menu\Built-In Classes\Movie\MovieClip\Methods\createEmptyMovieClip). Example:
_root.createEmptyMovieClip()
Movie clip methods include: play, stop, nextFrame, prevFrame, gotoAndPlay, gotoAndStop, duplicateMovieClip, startDrag, and stopDrag. Access them in the same fashion as above.
If a movie clip instance exists in the Timeline, it will play automatically. However, if you use ActionSctipt to create a movie clip dynamically, then you use the play method, which enables you to start the movie clip on a particular event. Example: play movie clip "mystar" when Play button is selected.
btn_play.onPress = function()
{ mystar.play(); }
To stop a movie that is playing. Example: stop the movie clip "mystar" when Stop button is selected.
btn_previous.onPress = function()
{ mystar.stop(); }
Controls the playhead. May be used to loop the movie where is can go back and forth from one frame to another. Example: to move the playhead in movie clip "mystar" to the second frame when the Next button is selected, and go back from the second frame when the Previous button is selected.
stop();
btn_next.onPress = function()
{ mystar.nextFrame(); }
btn_previous.onPress = function()
{ mystar.prevFrame(); }
Allows you to move the playhead to a particular frame in the movie and play or stop. (You can also use the nextScene method to go to the next scene.) Example: move the playhead in the movie clip "mystar" from the first to the tenth frame and play from there when you select the button b1.
stop();
b1.onPress = function() {
gotoAndPlay(10);
}
To duplicate a movie clip with all its inherent properties.
Used to drag a whole movie and drop it to another location.
Used to remove a movie clip from the Timeline.
OOP is based on objects and their properties. ActionScript breaks complex programs into smaller, related, and self-contained subgroups. Each self-contained subgroup is referred to as an object, which contains its own instructions and data that relate to that particular object.
In OOP, an object is a container that holds multiple data values in individually named properties and is modeled on real-world objects. Properties are variables defined on an object. To set or change the values of these properties, you need to use a method or a function. Different objects will have different properties. Objects with the same propeties belong to a class.
A class is a group of objects that have the same properties, common behavior, and common relationships. The properties of an object are derived from the class from which it is created. You can create any number of objects from a single class, each having the same general structure. For example, you can create several objects, such as cars, from the class Vehicles. Every program that employs the OOP approach includes at least one class, and certain programs may include several classes.
Whenever you are creating a program using the OOP concept, you first need to create one or more classes, depending on your requirements. Once you have created the classes, you need to create objects from them. Making or creating objects from classes is also called instantiating objects. After instantiating objects, you provide the instructions for the objects.
To create an object, use the var keyword, followed by the name of the object to be created, a colon, and the class from which the object is to be created. For creating an object, you also need to use the new operator with the class name and the function operator (). In the example, a new object named car is created from the class Vehicles.
var car:Vehicles = new Vehicles();
Each object has a distinct data value that can be stored in a variable. In the example below, the first line creates an object car from the class Vehicles. The second line assigns the value 100 to the speed property of the object car.
var car:Vehicles = new Vehicles();
car.speed = 100;
You may want to call or invoke a method anywhere in the program. Use the object name, followed by the dot operator ".", method name, and (). The example accelerates the object car.
var car:Vehicles = new Vehicles();
car.speed = 100;
car.accelerate();
To set a property for an object, specify the object name, followed by the dot operator ".", followed by the property, equal "=", and the value. The example sets the car's speed property to 100, then retrieves the value of the property speed and displays it.
var car:Vehicles = new Vehicles();
car.accelerate();
car.speed = 100;
trace (car.speed);
An object's method provides its behaviors and the object's properties store its data. Methods and properties can be either defined as private or public. When defined as private, they can be accessed only within that class. When declared public, they can be accessed anywhere in the program by all other classes.
Encapsulation is the process that allows selective hiding of properties and methods in a class from the rest of the program. To hide or encapsulate properties, define them as private inside the class. However you can access the encapsulated properties through the public methods defined inside the class.
Each class in a program defines a specific kind of data, which is represented as a data type in the program. These data types specify what values can be stored in a variable, used as a parameter, or passed as a return value. For example, while defining the speed property, specify its data type as Number.
var speed:Number
OOP allows a class to use the method and property definitions of another class. This feature is called inheritance. You can specify a hierarchical structure, so that many classes can use the features of a particualr class. This feature allows you to reuse code.
A class, which inherits properties and methods from another class, is called a subclass. And the class from which a subclass inherits properties and methods is called a superclass. However, a subclass can specify its own properties and methods in addition to those that it inherits from the superclass. A single supeclass can have many subclasses, but a subclass can have on one superclass.
Packages organize classes into organized groups. This way logical names (i.e., car) can be reused (i.e., factory.car, showroom.car) and naming conflicts between classes can be avoided. Just as two files of the same name can exist in two different directories on a computer, you can have two classes of the same name "car" placed in different packages named "factory" and "showroom". For example:
factory.car;
showroom.car';
There may be several subpackages inside a package, a.k.a. nested packages. When referring to a class in a nested package, you need to separate each package name with the dot operator. For example,
showroom.imported.Vehicles
(Instance and Class)
Just like files are stored in folders, classes store their information in properties. However, some information may relate to an individual object in a class. These properties are referred to as instance properties, which are stored individually on each instance of a class, and can be accessed only through the instances.
An instance property is declared only once for the entire class. Each instance of the class, however, maintains its own value. for example, the property, speed, of the class Vehicles is declared just once for the entire class. But each instance of the Vehicles class defines its own value for speed. Therefore, each instance will have its individual value for speed.
class Vehicles
{
//Instance property is declared just once for the entire class
var speed:Number;
}
Ideally, properties should be declared outside of the instance methods, as variables declared within a method are considered to be local variables, which cannot be accessed outside of that method code.
If you want to define an instance property, you need to use the var statement inside the body of a class. For example, to define property speed with the data type as Number and the value as 80, use the keyword var followed by the property's name, its data type, and value.
class Vehicles
{
//Declaration of the insance property with a value assigned to the property, speed.
var speed:Number = 80;
}
If you do not specify the data type of a property, no type checking is performed on the property. this means that you can store any type of value in this property. To omit a data type, all you need to do is leave out the data type declaration while defining the property.
//Declaration ofa property without specifyingthe data type
var speed = 80;
//The property, speed, stores a numeric value first and now a string value.
speed = "Fast";
You can modify property definitions by using the attributes, public, private, and static. These attributes specify how a property can be accessed and where a property can be accessed from. You need to list the required attributes before the keyword var in a property definition.
class Vehicles
{
//Use of the public attribute
public var speed:Number;
}
If a particular property has more than one attribute, they can appear in any order.
public static var speed:Number; //is the same as:
static public var speed: Number
As a general convention, the public attributes are placed before the static attributes.
Defining a property as public or private determines whether a particular property is accessible outside the class that defines it or not. In short, you can control and modify the accessibility of properties outside their respective classes. For this reason, these attributes are also known as access control modifiers.
You may want to make a property inaccessible to code outside a particular class. For this, you use the private attribute. for example, to make the properties speed and mileage inaccessible to code outside of the Vehicles class, you can use the attribute parivate while defining these properties.
class Vehicles
{
//Both properties are declared private and cannot be accessed from outside the class.
private var speed:Number;
private var mileage:Number;
}
Now, if you try to access one of these attributes from outside the Vehicles class:
var race:Vehicles = new Vehicles();
race.speed = 100;
...the compiler generates a runtime error "The member is private and cannot be accessed. race.speed = 100;"
If your property definition does not include the private attribute, by default, that particular property is considered as public. For instance, declaring the properties, speed and mileage, of the class Vehicles as public. If you specify the property speed to be public and do not specify any attribute for mileage, still, both of them will be treated as public.
class Vehicles
{
//Speed is declared as public
public var speed:Number;
//No attribute is declared for mileage, but is considered public by default
var mileage:Number;
}
The static attribute determines whether a property is associated with the instances of a class or with the class itself. Unless you specify the static attribute, the property definition creates an instance property by default. For instance, if you want to define the property, color, as static (e.g., of the class only), place the keyword static before the keyword var, and before or after the keyword public or private.
class Vehicles
{
static public var color: String;
}
Key Apsects of defining class properties:
By default, class property definitions create instance properties. To indicate to the program that a certain property is a class property, you need to use the keyword static while defining the class properties. Class properties are directly accessed through a class and are independent of any object instances. Unlike instance properties that vary from instance to instance, class properties are used to store information that relates logically to the entire class. You can use class properties for sharing data across objects of a class or between classes.
You can initialize class properties to any value, but the value
depends upon the position of the compiler in the program. For instance:
This will give you an error because the value of y is undefined before
it is assigned to x:
public static var x=y;
public static var y=10;
Whereas, this will not give an error:
public static var y=10;
public static var x=y;
Inside a class body, you can access a class property etiher by its name directly or though the class. In the example below, both statements access the same property but with different names.
class Vehicles
{
public static var speed:Number = 100;
public function showSpeed()
{
//Accessing the property, speed, directly by its name
trace("The speed of the vehicles is:" + speed);
//Accessing the property, speed, through its class name (BETTER)
trace("The speed of the vehicle is:" + Vehicles.speed);
}
}
Although the output for both statements is the same, accessing the propery through its class is the better approach, as there could be more than one class with the same property. In such a case, you would have to specify the class from which you want to access the property.
From outside the class body, you can only access a property through its class name. If the statements in the above example were written outside the class body, only the second statement would execute properly, whereas the first statement would give an error:
The speed of the vehicle is:undefined
the speed of the vehicle is:100
You cannot access a class property through an instance of the class, as it will generate an error. Static members can only be accessed directly through classes.
You can store only a single value in a class property. However, if the value changes, the change in the value is universal. The following example adds two methods to the Vehicles class, one to set the value of Vehicles.speed and one to retrieve it. Now, irrespective of which instance invokes the methods, they operate on a single value of the property speed.
class Vehicles
{
private var speed:Number;
private static var defaultSpeed:Number = 80;
public function setSpeed (s:Number)
{
if (s == undefined)
{
s = defaultSpeed;
}
speed = s;
}
}
As in the above example, a class property may be assigned a default value to cover instances where the property value is not assigned.
Along with class properties, ActionScript 2.0 supports global variables which are accessible from anywhere in a program (more commonly used in ActionScript 1.0). When specifying global variables, you do not have to specify the data type. However, Global variables are considered unsafe as they may lead to an unorganized structure and variable name conflicts. The syntax is:
_global.someVariable=someValue;
example: _global.speed=100;
Consider that you're working with multiple class properties and global variables and you want to use a single property across several classes in your code. Defining the property in all classes one-by-one may be time-consuming. An easier method is to include the property in a separate class and access this property through subclasses of this class. For example, the property speed in the class Vehicles needs to be accessed by another class car:
in file Vehicle.as:
class Vehicles
{
var speed:Number = 100;
}
in file car.as:
car extends Vehicles
{
//The car class is made as the subclass of the Vehicles class
}
After defining car as the subclass of the Vehicles class, you need not define the property speed again for the car class. Instead, you can directly access the property by its name in this class. The property speed is accessible through both, the main Vehicles class and the car subclass.
Vehicles.speed = 100; //Accessing speed from the main class
car.speed = 200; //Accessing speed from the subclass car
Note: ActionScript prevents access to inherited class properties before
the superclass that defines the property is used in a script.
A method is a specific set of activities. Once defined in code, methods can be reused at other places in the program by just calling it using the method name. Methods implement the tasks that the class, or instances of the class can perform. For example, the built-in MovieClip class has a method named loadMovie that loads the specified animation into the movie clip.
You can define methods for your own classes.
You can define methods by using the function statement within the body of a class definition:
Class className
{
function methodName (param1:type,...paramn:type):returnType
{
statements;
//Function body statements are written here
}
}
After the function keyword, you need to specify the name of the method followed by the list of parameters and their data types within parentheses. returnType refers to the data type of the method's return value. The statements inside the curly braces are the instructions that need to be executed when the function is invoked.
You can refer to the parameters of a function directly by name, provided you are referring to them inside the body of a method. For example, the method findSpeed defines parameters named distance and time. Now, you can refer to these parameters inside the method body directly by their name. The syntax for referring to the parameters inside the method body is shown below:
function findSpeed (distance:Number, time:Number):Number
{
return distance/time;
}
The cases in which you do not specifiy the parameter's data type, type checking is not performed for that parameter. This essentially means that any type of value can be stored in that particular parameter. Similarly, if the returnType is not specified, type checking is omitted for the return value of the method as well.
While specifyingthe returnType for a method, if you want that the method should not return any value, you need to use the Void data type. However, when you specify the returnType as Void, you need to ensure that is does not return any value. Otherwise, the compiler generates and error, such as:
**Error** C:\Flash\Vehicles.as: Line 15: A function with return type Void may not return a value.
Below is an example of a method named findSpeed. The method definition starts with the function keyword and is followed by the method name findSpeed. Since it does not take any parameter, the set of parentheses () for the parameter list is empty. Notice the return value of the method is specified as Number. When you call the findSpeed method, it returns the value of distance divided by time, which is a numeric value. The last part of the syntax consists of the statement block within curly braces. The properties distance and time are referred to directly by their names.
class Vehicles
{
public var distance:Number;
public var time:Number;
function findSpeed ():Number
{
return distance/time;
// properties distance and time are directly referred to by name
}
}
The method name and the accompanying parameter list together constitue the method signature, which serves as a unique identity for that method among the other methods of that class. Every method in a class should have a unique name. However, you can have methods of the same name in differerent classes. The method name findSpeed and the () is the method signature for the example below:
class Vehicles
{
public var distance:Number;
public var time:Number;
function findSpeed ():Number //the method name, findSpeed and the () are the method signature
{
return distance/time;
}
}
Core classes are used in most of the programming languages. These classes are also referred to as core ActionScript classes in Flash (based on European JavaScript type ECMAScript). For example, to perform mathematical computations, you can use the methods available in the Math class. The classes that are specific to Flash enable you to control the appearance and behavior of a Flash application at run-time. To access the core classes from the ActionScript window (F9), select + \Built-In Classes \Core
The core ActionScript classes are those classes you would find within any programming language and are referred to as: arguments, Array, Boolean, Date, Error, Function, Math, Number, Object, String, and System.
The arguments class functions like an array that stores the values passed as parameters to any function. Whenever you call a function in ActionScript, as "arguments" an object is automatically created for that particular function. A local variable called "arguments" is also created with this object. You can use this variable to refer to the arguments object.
Used to access and modify arrays. An array stores related pieces of data. Each item in an array is referred to as the array element and is accessed through a number called an index, starting with 0.
The Boolean class encloses all the Boolean values inside it. The Boolean values are either true of false. You can use the Boolean class to retrieve the primitive value or string representation of a Boolean object.
Used to access date and time values relative to the universal time or relative to the operating system on which Flash is running. The methods of the Date class are dynamic and apply on the individual Date object specified when invoking the method. Daylight Saving Time is handled differently by the Date class, depending on the type of operating system and the Flash player version on your system.
This class contains information about the errors that can occur on your script. Create an Error boject by using the Error constructor function.
The Function class represents all the ActionScript functions, both built-in and user-defined.
Enables you to access and manipulate numerical constants and functions
Encloses all primitive number data types
The Object class is at the root of the ActionScript class hierachy. It contains a small subset of the features provided by the JavaScript Object class.
This class provides methods and properties that allow you to manipulate the basic string value types. It also encloses the basic string data type. An important feature of the String class is that you can convert the balue of any object into a string using the String function.
This class provides you with the ability to determine information about the user's system settings, such as the screen resolution and current system language. It also gives information regarding the Flash player and the operating system on which it is running. Additionally, it allows you to modify the Flash Player and file security settings to match the needs of each user.
These ready-made classes are for developing animations in Flash and come in four categories: Media, Movie, Client/Server, and Authoring.
(+ \ Built-In Classes \ Media)
(+ \ Built-In Classes \ Movie)
The Movie class helps control visual elements in animations and the Flash Player:
(+ \ Built-In Classes \ Client/Server)
The Client/Server classes allows you to work with XML and other external data sources:
(+ \ Built-In Classes \ Authoring)
The Authoring Classes provide control over the Flash authoring environment. It allows you to install of uninstall the custom actions.:
To define a class you must use a class declaration. Class declarations start with the keyword class followed by the name of the class, which is case-sensetive. Standard convention is that a class starts with a capital letter.
class Vehicles
{
\\this is the class body
}
The class definition resides in an external text file with the .as extension. This file should contain only one class definition and the file name must exactly match the name of the class it contains (i.e., Vehicles.as). If you incorrectly specify the filename (i.e., Automobiles), Flash displays an error message (i.e., The class 'Vehicles' could not be loaded.)
The class definition block is all that is contained between the braces and may include the following. Avoid nesting class definitions and using raw code inside the class as this will result in compile time errors (i.e., This statement is not permitted in a class definition.)
The methods and properties of a class are known as its members. When you refer to a class member, it can imply either a class property or a class method.
You must define members of a class with the class statement itself. If you try to add a method or property to a class from outside the class definition, the compiler generates an error. For example, you create the Vehicles class and then create an instance and try to give it a new property, say speed. You would get this error "there is no property with the name 'speed'".
You can modify class definitions using one or both of the class attributes, dynamic and intrinsic. The attributes you specify will decide how a class and its instances can be used in a program.
If you define the class with the dynamic attribute, new propeties and methods can be added to the classes instances and the class itself from outside the class and the code will execute without errors. This gives special behavior to the built-in ActionScript classes. When the MovieClip class is defined as dynamic, it allows instances of this class to take on new properties and methods. This means that we can define new properties for these instances, which are not in the original MovieClip class.
dynamic class Vehicles
{
//Class body with dynamic attribute
}
If you intend to use the dynamic class for a property or a method, which is applicable to all the instances of the class, you can add it to the class definition self. However, if the property or the method is not applicable to all the instances of the class, you need to create a subclass of the original class and add the new property or method to the subclass. Therefore, without using the dynamic attribute, you can create intsances of this subclass.
class Vehicles()
{
// No need to define the class as dynamic to use these properties in all it's instances
var speed:Number = 80;
var color:String = "Red";
}
The intrinsic attribute is most commonly used with built-in classes of Flash. This attribute is used to make changes to a compiled class, without disturbing the source code of that class. A class with the intrinsic attribute does not include any method body or property values, but just specifies their names and data types for compile-time checking. For instance, the LoadVars class is built into the Flash player and the source code is not available to the compiler at authoring time. The compiler uses the intrinsic class definition to perform type checking on LoadVar instancers at compile time.
dynamic intrinsic class LoadVar
{
var contentType:String;
var loaded:Boolean;
function getBytesTotal():Number:
function toString():String;
}
An entire class can inherit methods and properties of another class. This allows you to structure an application's hierachy so that the new classes can reuse the methods and properties of existing classes. This concept improves efficiency and saves time.
The class that is inherited is called the superclass and the class that inherits is known as the subclass. The methods and properties of the superclass do not undergo any change. For example, the class Cars inherits the methods and properties from the class Vehicles by using the keyword "extends". As a result, the value of the property speed, defined in Vehicles, doesn't change when accessed from the subclass Cars. The example shows the properties of the class Vehicles and the subclass Cars, the ActionScript that acts on them, and the resulting output.
in file Vehicles.as:
class Vehicles
{
public var speed:Number = 100;
public static var mileage:Number = 10
public static function getMileage():Number{
return mileage;
}
}
in file Cars.as:
class Cars extends Vehicles {
}
in ActionScript:
var carsA:Cars = new Cars();
trace ("Speed = " + carsA.speed);
output:
Speed = 100
In addition to inheriting the methods and properties of Vehicles, the Cars subclass can define its own methods and properties. This makes the subclass a superset of the features defined in its superclass Vehicles. Instances of the Cars class can access the methods and properties of both Cars and its superclass Vehicles. The example below shows the properties of the Cars class and the values being set by actionScript, including the speed property inherited from the class Vehicles.
in file Cars.as:
class Cars exgtends Vehicles{
public var noDoors:Number;
public function setnoDoors(tnoDoors:Number):void{
noDoors=tnoDoors;
}
}
in ActionScript:
var carsA:Cars = new Cars();
carA.noDoors = 4;
carA.speed = 110;
The properties of a class may be inherited by more than one subclass. This includes subclasses inheriting properties and methods from other subclasses, along with the properties and methods of its superclass. For example, the Convertibles subclass of Cars, inherits Cars properties and methods, as well as those of Vehicles. A superclass is unaware of the subclasses that inherit it. The information about the subclasses inheriting the superclass is hidden from the superclass.
In addition to non-static methods and properties, a subclass also inherits those methods and properties of its superclass that are defined with the static attribute. The example below shows you can access the class method getMileage defined in Vehicles from both Vehicles as well as Cars. You should use the class name and not its instance when referencing class methods or properties.
in actionScript:
trace ("Vehicles Mileage = " + Vehicles.getMileage());
trace ("Cars Mileage = " + Cars.getMileage());
output:
Vehicles Mileage = 10
Cars Meleage = 10
A subclass is known as a subset of its superclass because you can substitute a superclass's instance with the instance of its subclass. For example, you can assign an instance of Cars to a variable of class Vehicles. This can be done because the compiler is aware that any instance of the subclass Cars contains all the methods and properties defined in the superclass Vehicles.
var vehiclesA:Vehicles;
vehiclesA = new cars ();
Keep in mind that you cannot assign an instance of Vehicles to a variable of type Cars. In this case, the compiler throws a type mismatch error because an instance of Vehicles may not contain all the methods and properties defined in Cars.
in ActionScript:
var carsA:Cars;
carsA = new Vehicles():
output:
Type mismatch in assignment statement: found Vehicles where Cars is
required.
carsA = new Vehicles();
ActionScript lets you create packages to logically organize classes and interfaces. Packages also enable multiple classes of the same name to coexist without any naming conflict. A package name describes the classes within it. You refer to a specific class within a package by using the dot operator (.). For example, to refer to the class Vehicles in the package ohioFactory, you'll use the syntax
ohioFactory.Vehicles
By convention, when naming packages you should use mixed case, as in the example above. Ideally, packages should reside in a package named after your organization's domain name. for example, ohioFactory is placed in the package com.faircomanufacturing. You can even include the department name in the package hiearchy, say, com.faircomanufacturing.production.ohioFactory.
Just like a folder hierarchy, you can nest a package inside of another. When refering to a nested package, separate each package name with the dot operator. Also, a package with the same name can reside in different packages. For example:
com.faircomanufacturing.production.ohioFactory.Vehicles
com.faircomanufacturing.sales.ohioFactory.Vehicles
In addition to containing other packages, a package can contain other classes, as well.
To define a package for a class, first create a directory structure in the order of the package hierachy, and then specify the package name in the class definition. The package name is defined in the definition of the class .as file.
in file Vehicles.as:
class com.faircomanufacturing.production.ohioFactory.Vehicles {
//class body...
}
A package does not have a specific package file. The concept of a package involves placing the .as file of a given class file under the appropriate directory. If the package or class name specifed in the class definition does not match the system directories, the compiler throws an error, such as:
'com.faircomanufacturing.production.ohioFactory.Vehicles' needs to be defined in a file whose relative path is
com\faircomanufacturing\production\ohioFactory\Vehicles.as
If a class exists within a package, you need to refer to the class by including its complete package name, known as a fully qualified reference. You need to use the fully qualified reference of Vehicles when creating instances of it. For example:
var vehiclesA:com.faircomanufacturing.production.ohioFactory.Vehicles =new com.faircomanufacturing.production.ohioFactory.Vehicles();
On the other hand, if a class is not included in a package, you use the unqualified reference that consists of only the class name. Say, the class Vehicles is not within a package. Now, when you create instances of this class, you would use its unqualifed reference:
var vheiclesA:Vehicles = new Vehicles();
You can use the import statement to substitute the fully qualified reference of a class with its unqualified reference. The syntax of the import statement is shown below:
import com.faircomanufacturing.production.ohioFactory.Vehicles;
var vehiclesA:Vehicles = new Vehicles();
The import statement can be used only when classes are incuded in packages. To compile imported classes into a movie, you need to reference them in the Flash document.
When you include a class in the import statement, say Vehicles, the compiler imports only this class and not the other classes in the package. To import all the classes in the package, such as Cars and Bikes, you should use the wildcard syntax or asterisk, as shown below. In this syntax, you refer to any class in the package by using its unqualified reference rather than its fully qualified reference.
import com.faircomanufacturing.production.ohioFactory.*;
var vehiclesA:Vehicles = new Vehicles();
var carsA:Cars = Cars();
Using the wildcard, or asterisk syntax to import two classes with the same name residing in different packages can be tricky, as you'll encounter a namespace collison. In this case, you have to use the fully qualified rederences of the classes. The syntax to access the class Vehicles from the packages com.faircomanufacturing.production.ohioFactory and com.faircomanufacturing.sales.ohioFactory is shown below.
import com.faircomanufacturing.production.ohioFactory.*;
import com.faircomanfacturing.sales.ohioFactory.*;
var vehiclesA:com.faircomanufacturing.production.ohioFactory.Vehicles = new com.faircomanufacturing.production.ohioFactory.Vehicles();
var vehiclesB:com.faircomanufacturing.sales.ohioFactory.Vehicles = new com.faircomanufacturing.sales.ohioFactory.Vehicles();
To access a class in a package from a .fla file, the root directory of the package must be within the classpath used by the compiler. Classpath is the path to the directories containing your classes and can be global or document. The global classpath includes the current directory and the Classes directory under the user configruation directory and is applicable to all. fla files. the document classpath is applicable only to the .fla file in which it is specified. Setting the classpath for all or document is described below.
To make the class Vehicles accessible to ALL .fla files, add the package root directory of the class Vehicles to the global classpath. (Edit\Preferences\ActionScript\ActionScript Settings). Select the + to add, then click the target icon and select the path (i.e., com\faircomanufacturing\production\ohioFactory).
To make a class available to only ONE .fla file, say the class Trucks to be accessible only within the Trucks.fla file, add the package root directory of the class Trucks to the document classpath. (File\Publish Settings\Flash\Settings) Add the path as above.
ActionScript has various functions and methods that enable you to connect to external data for sending and loading information into a Flash file. Like HTML pages, Flash animations can retrieve and display information. Flash .swf files improve on this functionality because they remain loaded in the web browser and constantly update new data without having to reload the entire page.
By default, an animation can only access data from the same domain to which the Flash movie belongs. You can, however, send and retrieve information to an animation from external data sources, such as text files, by using ActionScript functions and methods. Note that every single function or method uses aprotocol to transmit data that has to be formatted in a specific manner.
Use the ActionScript functions and MovieClip methods, LoadVars methods, Extensible Markup Language (XML) methods, and XMLSocket methods for exchanging information between an animation and external data sources.
The functions and Movieclip methods that can communicate with server-side scripts are getURL(), loadVariables(), loadVariablesNum(), loadMovie(), and loadMovieNum(). Use these functions and methods to load variables processed by server-side scripts into a specified movie clip. These functions and methods use the HTTP or HTTPS protocols and require data to be encoded in the URL format. These functions can also be used to load data and movie clips from the same directory as the SWF file, without server-side scripts.
The load(), send(), and sendAndLoad() methods of the LoadVars class transmit information between an animation and a server by using the HTTP or HTTPS protocols. These methods can process data that is in the URL-encoded format. Using the LoadVars methods, you can transfer variables between an object and a specified URL. See LoadVars Class, below.
Use the XML.send(), XML.load(), and XML.sendAndLoad() methods of the XML class to send and receive information into an animation in the XML format. These methods use the HTTP or HTTPS protocols and allow you to transfer structured XML data to a server. You can also use these XML methods to manipulate and interpret downloaded XML data.
The XMLSocket.connect() and XMLSocket.send() methods create and use a TCP/IP socket connection to send and load information as XML. These methods allow you to create a continuous connection with a server, which greatly reduces communication delay time. For this reason, theXMLSocket methods are widely used to develop real-time applications such as chat.
You can also use server-side scripts for loading information into an animation from a database. Server-side scripts are programs stored on a web server, which control certain functions such as linking animations to databases. These scripts can be written using various languages such as ColdFusion Markup Language (CFML), Practical Extraction and Report Language (Perl), Active Server Pages (ASP), and PHP Hypertext Preprocessor (PHP).
CFML is one of the commonly used server-side scripting languages that supports dynamic web page creation and database access in a web server environment by importing content into an animation. Perl, on the other hand, offers strong text processing abilities and is widely used for writing Common Gateway Interface (CBI) scripts, which facilitate transfer of data between a web server and an application program.
You can use ASP to transfer data between an animation and Microsoft Windows servers. ASP is a compile-free application environment that enables you to create dynamic and secure pages. Additionally, you can import data into an animation with PHP, which is a cross-platform, HTML embedded scripting language. You can create dynamic an personalized content for your animation using PHP.
The LoadVars class offers various methods to transfer external data to a Flash document. You simply need to create a LoadVars object that will contain the loaded data. LoadVars methods essentially transfer data, such as a text file, stored in the form of variables. You can also call these methods to load all varibles from a specified URL into an object and transfer all the varibles in that object to a specified URL. These are the steps for loading external data with the LoadVars object:
Scenario: You can load a list of names from a database stored in a text file into an animation. Let's say, you have stored the name Debbie Howe in a text file named UserName, and now you want to display it in a text field in your animation. You can do this by using the LoadVars object.
firstname=Debbie&lastname=Howe
var nameVars = new LoadVars();
//Defines a new LoadVars variable named nameVars
nameVars.onLoad = function(ok) (
//Attaches the onLoad event to nameVars
if (ok) (
name_txt.text = nameVars.firstname+" "+nameVars.lastname;
//Loads the variable nameVars into the dynamic text field name_txt
)
);
nameVars.load("UserName.txt);
//Loads the data in the text field Username.txt to nameVars
You can transfer data between and animation an server-side scripts using several ActionScript functions and MovieClip methods. Choose the function or method depending on how you want to load data into your animation. These functions and methods use the HTTP or HTTPS protocols and require data to be encoded in the URL format.
For loading varibles processed by server-side scripts into the Timeline to which the function is attached, use these functions:
Use these MovieClip methods to load the processed variables into the movie clip:
Remember that each function and method returns data in a specific manner. Like, loadVariables() loads varibles into a specified Timeline in the Flash Player, whereas, loadVariablesNum() sets the values for variables in a Flash Player level. The getURL() function returns data to a browser window instead of the Flash Player. TheloadMovie() function loads a .swf file or a JPEG image into a movie clip in the Flash Player, whereas, loadMovieNum() loads into a specified Flash Player level.
MovieClip.loadVariables() sets the values for variables in a specified movie clip. MovieClip.loadMovie() loads .swf files or JPEG images into a movie clip in the Flash Player while the original animation is still playing. The MovieClip.getURL() method loads a document from the specified URL into the specified Flash movie.
When you use the functions and MovieClip methods, you can specify several parameters such as URL, location, and variables. The URL parameter specifies the name of the file that contains remote variables. The location paramter lets you define the level or target in the animation that receives the variables. The variables parameter specifies the HTTP method, GET or POST, by which the variables are sent.
For example, to automatically update data in your animation, say stock prices, you need to load data into the file from a server. To do this, use the syntax displayed below to call theloadVariables() function. This syntax loads the variables from the ColdFusion script called StockPrices.cfm into the movie clip instance stockPricesClip using the GET HTTP method.
loadVariables(
" http://www.faircomanufacturing.com/scripts/StockPrices.cfm", _root.stockPricesClip, GET);
Remember that the script file specified in the URL parameter of loadVariables() must contain data in variable and value pairs format. Also, you need to separate each pair with an ampersand. Further, separate words within a value using a plus sign. The variable and value pairs specified in StockPrices.cfm are shown below.
stockPrice1=350.47&company1-Fairco+Manufacturing&stockPrice2=450.85&company2=Diligent+Insurance&stockPrice3=275.35&company3=Flysafe+Corporation&stockPrice4=350.47&company4=Barny's+Bank
All variables loaded with the loadVariables() function must be in the standard Multipurpose Internet Mail Extension (MIME) format. MIME is the standard format used by ColdFusion Markup Language (CFML) and Common Gateway Interface (CGI) scripts.
Unlike HTML, XML tags do not need to be predefined. Also, XML documents can be re-used in different environments.
With Flash, XML helps entegrate external data into your Flash application. To do this, use either the methods of the XML class or the XMLSocket class.
The XML class enables structuring of external data in Flash and includes these methods (Actions Panel\Add\Built-in Classes\Client/Server\XML\Methods):
You can also send the XML data to a server and modify and interpret downloaded XML data by using methods such as load(), send(), and sendAndLoad().
You can use the load() method to download XML from a URL and place it in an ActionScriptXML object. You can encode this object into an XML document and send it to the specified URL using the send() method. The sendAndLoad() method allows you to send an XML object to a specified URL for processing. The server's response for this processed information is then downloaded and stored in an XML object specified in the parameters.
For example, imagine the user enters a user name and password in the login screen of a Web page, which may be an animation. Using ActionScript, the information entered in the animation is converted to an XML object and sent to the server-side script as an XML document. Similarly, you can also load the XML document that the server returns into an XML object to be used in the animation.
The XML Socket class enables sending, loading, and interpreting downloaded data and is very important when real-time applications are involved, as in a Chat application, for example. The XMLSocket class establishes a socket connection allowing the server to publish or push the information to the client as soon as that information is available.
The XMLSocket class includes these methods (Actions Panel\Add\Built-in Classes\Client/Server\XMLSocket\Methods):
The methods available in the XMLSocket class are close(), connect(), and send(). The close() method, as the name indicates, closes the socket connection. The connect() and send() methods transfer XML data to a from a server over a socket connection. Basically, the connect() method establishes a socket connection with a web server port and the send() method passes an XML object to the server specified in the socket connection.
When you invoke the connect() method, the Flash player opens a TCP/IP connection to the server. This connection stays open until the close() method is called or until the time when there are no more references to the XMLSocket object available. The connection may also be closed if you exit the Flash player or there's some problem with the physical connection.
When developing a Flash application, the task of creating labels, check boxes, radio buttons, and buttons is simplified by using the built-in components. A component can be anything from a plain user interface (UI) control, such as a button or a label to an entire window that can hold other elements. Some components are non-visual, such as the Focus Manager that enables you to manage which object gains focus in an application. All you need to do is drag these components from the Components panel to add them to the application and tailor thelook and feel as needed.
Components are built on the Macromedia Component Archetecture version 2(v2) and written in ActionScript. Every component is a class and each class is contained in an ActionScript package. for instance, a check box component is an instance of the CheckBox class, which is contained in the package mx.controls. Almost all v2 components are subclasses of the UIObject and UIComponent classes and inherit all methods, properties, and events from these classes. Additionally, several components are also subclasses of other components. for example, the Label component is a subclass of the UIObject class.
Basically, components are movie clips that have parameters for modifying appearance and behavior. This means that when creating a Flash application, you can modify these predefined parameters and make these components fit your requirements. You can also set values for these parameters and add more options dynamically by using ActionScript methods, properties and events.
Components allow you to segregate the designing part of an application from the coding part. For example, you can change the appearance of a component on the Stage. But this will not change its functionality defined in its class file. The biggest advantage of components is reusability because you can reuse components over and over again. Also, v2 components offer core functionality such as event handling, styles, skinning, and focus and depth management.
When using any v2 component in an application, the size of the Flash document increases by almost 25Kb due to core functionality. This functionality is reused for any additional components and therefore the file size increases only marginally irrespective of the number of components added. However, when you don't use any v2 component, the file size is reduced but it results in adding extra code for creating components.
V2 components appear as compiled clip symbols in the Components panel. Compiled clips basically consist of built-in live previews and are not modifiable. However, you can alter their paramters by using the Component Inspector and Properties panels. A compiled clip contains precompiled symbols and ActionScript that do not change and therefore can be used as components in the Flash document. These clips can be published faster as compared to regular clips.
You can use components as UI, media, and data components and managers. UI components enable you to interact with your application whereas media components add life to your application. You can insert data from data sources and manipulate it by using data components. Managers, which are non-visual components, enable you to control a feature, such as focus or depth, in an application.
In addition to animations, Flash also lets you create interactive Internet applications. And to create forms for such applications, the user interface (UI) components displayed in the Components panel come in handy. These components enable users to interact with a form or an application. To display the Components panel: click Window\Development Panels\Components OR press Ctrl+F7.
The built-in components are Button, CheckBox, ComboBox, Label, List, Loader, NumericStepper, ProgressBar, RadioButton, ScrollPane, TextArea, TextInput, Window. Components are .swc files used to save and distribute components.
Adding a built-in UI component in a Flash document:
When you add a component to the Stage, it is displayed as a compiled clip symbol in the Library panel (click Window\Library OR press Ctrl+L). To add another instance of the Label, you can drage the component's icon from the Components panel or Library, as appropriate.
To set and view parameters for a component, access the Properties panel. Alternately, you can use the Component Inspector panel (click Window\Development Panels\Component Inspector OR press Alt+F7).
When a component is selected, the Properties panel displays two tabs, Properties and Parameters. In the Properties tab, you can specify the size and position of the component using the W,H, X, and Y options. You can also enter a name for the component in the Instance Name box.
The Parameters tab is similar to the Component Inspector, displaying the most frequently used properties and methods, which appear as authoring parameters. You'll have to set the remaining parameters using ActionScript. All parameters that you set during design time can also be set during run time with ActionScript. If you've changed the value of a parameter during run time, the value that you've set during design time will be superseded.
To delete added components, select the compiled clip symbol of the component in the Library panel. Right-click to display the shorcut menu and select Delete. Confirm the deletion.
Apart from the Components panel, you can also use ActionScript to add a built-in component.
createClassObject(mx.controls.Label, "lbl", 5, {text:"First
Name"});
You can customize a component in more than one way. For example, you can alter the color or text format of a component by using styles. You can even modify or replace the source graphic to change the complete appearance of a component. This process is referred to a skinning. In addition, you can apply different themes that contain styles and skins to give your interface a different look. Each Flash component has its own color and text formatting style properties. You can use the setStyle() and getStyle() methods to alter and view these style properties of any component.
Styles specify color or text format of a component. Color style properties have a name that ends in "Color", and the value of these properties can be a number, a string, or an object.
Each Flash component comprises graphic or movie clip symbols referred to as skins. For example, the down arrow of the ScrollBar component. This arrow consists of the ScrollDownArrowDisabled, ScrollDownArrowDown, ScrollDownArrowOver, and ScrollDownArrowUp skins. To replace the appearance of this down arrow, just replace all the skins. You can have skins that contain only ActionScript code. You can draw the component in the Flash document using the ActionScript code.
Each skin has a property assigned to its symbol's Linkage Identifier. Referring to the Linkage Identifier of a component in the ActionScript, you can use the skins for any component. You can modify skins using the skin properties rather than modifying the ActionScript to load specific skins for the component. For example, the pressed state of the down arrow of ScrollBar has the property downArrowDownName. The Linkage Identifier of this property is ScrollDownArrowDown.
Skins can also be shared between components of a document. For example, ComboBox uses scrollbars. If you have a ComboBox and ScrollBar in a document, ComboBox can share the skins from the ScrollBar Skins folder. However, if you want to use different skins for different instances of a component, you can modify the existing skin and set its properties.
After modifying the skin, the next step is to apply the modified skin to a component. If you want to create the component instances dynamically, you need to use the createClassObject() method. Alternatively, you can manually position the component instances on the Stage. You can also modify the skins of a subcomponent of a component.
A theme is a group of styles and skins. Themes allow you to change the appearance of all the components in an application. Flash displays the Halo theme by default. In addition to the Halo theme, it includes the Sample theme. Flash not only allows you to alter these themes but also allows you to create new themes to suit your needs. When creating new themes, you can use the ActionScript code to modify the skin sizes. Flash lets you create two-dimnesional as well as three-dimensional themes.
To apply a theme:
You can create components in Flash to meet your application needs. Essentially, a component is a combination of a Flash file and an ActionScript file. You can also create other files, such as an icon, and package it with the component. After you develop a component, you export it as a Shockwave Component (SWC) file and store it in the Flash Components directory. To create a component, you first need to design its framework and then write an ActionScript for it.
Designing a framework is the first step towards creating a component. Only when you design the framework can you write the ActionScript to make the component work. Designing the framework basically includes createing new layers for the component and adding graphical assets.
Steps to create a component in Flash:
To extend an existing component, you first need to import that component and other required base classes from the external library using the import command. The base classes will then appear in your component's library. Select the symbol from the Components panel and place an instance of it in the SECOND frame of the component's Assets layer.
Note: You need to place the instances of all the assets your component uses inside the component.
You can enhance the appearance of your component by adding graphical assets such as different types of borders. Remember to add these assets on the second frame of your component's Assets layer.
Writing an External ActionScript
You can create a component using the class file of some other component. This is referred to as deriving a component from a parent class. For creating such a component, you need to write an external ActionScript class file and link it to the respective component. the ActionScript needs to extend another class and add methods, getters, and setters. Also, it should define an event handler for the component.
Steps for writing ActionScript for Components
Example using NavigationalPanel as the component name with nav links to Macromedia, Google, and Yahoo:
//import all necessary classes
import mx.core.UIComponent;
//define a class
class NavigationalPanel extends UIComponent {
//define variables The symbolOwner variable is the fully qualified package name of the component's class. The symbolName variable is the name of your ActionScript class and matches witht eh symbol's Linkage Identifier. When setting style properties, use the classNameVariable, which is the name of the component class.
static var symbolOwner:Object = NavigationalPanel;
static var symbolName:String - " NavigationatlPanel ";
var className:String = " NavigationalPanel ";
//add static versioning info - remember to update when updating component
static var version:String = "1.0.0.1";
//enter default member variables for the component and create variables for every skin element used in the component. This would help modify skins during authoring and at runtime, if required, just by changing a parameter in the component.
private var _captionStyles:Object =
{
color : 0x2B333C
,fontSize : 9
,fontFamily : "Verdana"
,fontWeight : "normal"
}
//assign constant values to variables (class constants)
private var _borderWidth:Number = 2;
private var _margin:Number - 5;
private var _spacing:Number = 2;
//add a metadata keyword and declaration for every variable that has a getter or setter. You use the metadata tags in your external ActionScript class files to define component attributes, data binding, properties, and event. Flash allows metadata tags only in the external .as file. This example uses the Inspectable metadata keyword.
[Inspectable( type="Array",defaultValue="Macromedia,Google,Yahoo" )]
[Inspectable( type"Array",defaultValue="http://macromedia.com,http://google.com,http://yahoo.com" )]
//add the component parameters to define look and performance. to provide visibility tot eh component properties, you define the getter or setter methods. When other Flash objects need to use the component, these getter/setter methods manage the access of these objects to the component properties.
private var _labels:Array;
private var _links:Array;
private var _linkTarget:String;
private var _captionText:String
public function set buttonLabels( labels:Array ):Void
{
_labels = labels;
invalidate();
}
public function get buttonLabels():Array
{
return _labels;
}
public function set buttonLinks( links:Array )
{
_links = links;
}
public function get buttonLinks():Array
{
return _links;
}
//add a constructor function to set properties and perform other tasks when a new instance of a component is detected. It should have the same name as that of the component class. Flash allows only one constructor function in a class.
function NavigationalPanel()
{
trace( "new NavigationalPanel" );
}
//add initialization size. This helps in outlining the contents of the component. Here, the size method calls the superclass's size method.
function size(Void):Void
{
trace( "size" );
doLayout();
super.size();
}
//Finally, add custom methods. Remember, custom methods override other inherited methods.
}
Flash allows you to export components as component packages, aka Shockwave Component (SWC) files. An SWC file is a compressed file generated by the Flash authoring tool. This file is comprised of the entire ActionScript code, SWF files, images, and metadata associated with the component. If you want to have access to the component's source code, you can include a Flash file and a read me file in the SWC file.
The learning interactions available in Flash enable you to create a dynamic and interesting learning environment. Learning interactions are components that can either be a part of an online quiz or an instructional document. You can easily implement and configure them in a Flash document. All Flash interactions have complete multimedia support including sound, text, and images.
Flash includes six learning interactions: True or False, Multiple Choice, Fill in the Blank, Srag and Drop, Hot Spot, and Hot Object. Each of these has certain parameters that determine how the interactions will appear to the user.
You can include the learning interactions using either the quiz templates of the stand-alone interactions method.
Quiz Templates minimize your efforts in keeping track of a user's scores. For example, a template may have a mechanism to count a cumulative score when the user solves the quiz.
Stand-Alone Interactions allow you to use either a single interaction or a sequence of interactions based on your requirements. For example, if you want an instructional piece with only a Multiple Choice interaction, you use the stand-alone interactions method. You can find these interactions in the common Flash library.
To calculate and track the score of the user for each interaction, you must install a server-side learning management system (LMS). Each learning interaction enables you to send tracking information to the LMS that are Aviation Industry Computer-Based Training Committee (AICC) and Shareable Content Object Reference Model (SCORM) compliant. AICC and SCORM are standards for online training compatibility. Note: You can initialize SCORM tracking only when you use quiz templates.
Flash provides three quiz templates. Each of these templates has a differnet graphical appearance. In addition, all the templates include sixa types of learning interactions. To create a quiz, you can select the template from the New Document dialog box.
Steps for Creating a Quiz:
Modifying Learning Interactions
Each question in the quiz represents an interaction. In a quiz
template, the first and last frames on the Timeline are reserved for
the Welcome page and Results page. You can add or remove frames and
keyframes to position interactions sequentially between the first and
the last frame. The number of frames between the keyframes Welcome and
Results page, help calculate the quiz score.
To modify learning interactions, you first select the first frame in the interactions layer and later the text of the Welcome page. Next you select each interaction and configure it as needed. Finally, select the last frame to modify the text of the Results page.
Each quiz template includes the six types of learning interactions, each having an associated component. You can configure this component to suit your specific requirements.
Steps to Configure a Learning Interaction:
Each learning interaction has its own default assets that are collectively stored within the movie clip symbols in the library. You can also enter your own instance names for grahpic assets. But to use these assets, you need to ensure that these are properly named an resgitered.
Each Flash learning interaction consists of four assets that include interaction components, dynamic text fields, distracter elements, and user interface (UI) components. Interaction components are basic quiz components whereas dynamic text fields give relevant messages to users based on their selection. Similarly, distracters are the answer choices of a quiz and UI components help users respond to quiz questions.
If you use similar interaction types (i.e., two or more Drag and Drop, etc.) in a file, you need to uniquely name each UI component. For example, the UI components in a Multiple Choice interaction are CheckBox and Button. When you create two Multiple Choice interactions, you need to give unique names for these components in the second interaction. Additionally, you need to register these new instance names in the interaction component parameters.
Steps for Naming and Registering Assets
Additionally, you need to specify unique instance names for the graphic distracters in all the interactions. For example, in a Drag and Drop interaction, the graphic distracters are the Drag objects and Target objects. If you duplicate this interaction, you will have eight Drag objects in the file. You would need to give unique instance names to each of these eight Drag objects.
On the other hand, dynamic text fields can have the same instance names across multiple interactions. This implies that you can enter identical instance names for the question text fields in both the Drag and Drop interactions. However, you need to register these names with the interaction component parameters just as you do for all other assets.