ActionScript Programming/Printable version
This is the print version of ActionScript Programming You won't see this message or any elements not part of the book's content when you print or preview this page. |
The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/ActionScript_Programming
PartI/Getting Started
Before starting reading the book, you need to know how to use the “Actions” window.
Actions toolbox is used for helping you to write script. The script is written in Script pane. There are 2 modes of programming in Flash MX. The first one is Normal Mode, which is for beginners and the code is written with the help of Actions Toolbox and Expression text field, and the second one is the Expert mode, which consists only of Actions Toolbox and Script Pane. If you use Normal Mode, then the Expression text field helps you to write the expression in it. And the Actions Combo Box is used to navigate from one object to another.
AS In A Nutshell
AS in a Nutshell
editSetting up an ActionScript application
editTo get started coding in ActionScript 2.0 (or AS 2.0 for short which is how I will be referring to it from now on), start up the Flash MX 2004 or later program. Then create a New Flash Document. When your new Document comes up, go to where the Timeline is and click the first frame of Layer 1. Now open up the Actions panel by either clicking on the Actions pane on the bottom of the screen or going to the File menu and clicking Window>Development Panels>Actions. Anything you type in here will be run first when you run or test the Flash movie. Now let’s create a simple program.
Put this code into the Actions panel:
myName = "Robert"
trace("Hello " + myName);
PartI/Chapter 1
Properties
editEvery Symbol instance in Flash has properties, which control the object itself and how it is displayed and its interaction with the environment. However, Graphic type symbol instances cannot be referenced with action script, since you can´t assign them an instance name.
Actionscript 3.0
Actionscript 3.0 removes the leading underscore for the various properties.
Properties in ActionScript contain an underscore before the property name, to indicate that it pertains to the display or environment. The properties of a symbol instance can be modified in design time or in runtime using action script, an essential task for animation.
In this chapter we will learn to use properties.
X, Y Coordinateseditx and y are the coordinates of the object. As the screen is 2D the object doesn’t have the 3rd z coordinate. Now let's write a small program. We will draw a ball and then move it to a specified location. Step 1 Select the oval tool from the toolbar and draw a circle. Step 2 Select the oval you have drawn and press F8. "Convert to Symbol" dialog will appear. Type "mov_ball" in the "Name" field, choose "Movie Clip" behavior and press "OK" Step 3 Now select the oval. In the properties window (at the bottom of the screen by default) in the "Instance Name" field (Near "Swap" button) type "ball". Now we can customize our ball’s properties. Step 4 Right click the keyframe in the "Timeline" window and choose "Actions". "Actions" window will appear. In the Script pane write the following: ball._x = 200;
ball._y = 200;
This example will set the position of the ball to (200, 200). But let's analyze the code. "ball" is our object in the scene. "_x" is the x coordinate of the object and "_y" is the y coordinate of the object. In ActionScript, the properties begin with "_" including the x and y coordinates. In many languages, ";" is put after each line, so that the program could find the end of the statement. |
Width, Height Measures
editWidth and height are the vertical and horizontal sizes of the object. The use of them are just as the use of x and y properties. Add the following lines to the previous example and you will understand.
ball._height = 50;
ball._width = 100;
XScale, YScale
editScaling the local coordinate system affects the _x and _y property settings, which are defined in whole pixels. For example, if the parent movie clip is scaled to 50%, setting the _x property moves an object in the movie clip by half the number of pixels as it would if the movie were set at 100%.
Visible
editThis property makes the object visible and invisible. To test this property we will need to add one button to the scene. Draw something like button in the scene and convert it to button (using F8), or you can just add the any button from "Common Libraries" in the "Window>Common Libraries" menu. After you have added the button right click it and choose "Actions" from the popup menu. In the Script pane type the following:
on (release) {
ball._visible = false;
}
But note, if you are using the Normal mode then don’t write this. Choose "Properties" from the left side of the "Actions" window and then double click "_visible". You will notice than the first and third lines will be written automatically, but the second line will just be "_visible". In the "Expression" field above the Script pane write "ball._visible = false". But if you are using the Advanced mode, then copy all the code written above. The first line is the beginning of "Release" event. "Release" event occurs when the user clicks the button. The structure of writing events is "on (<name of event>) {". The "{" tells the program the beginning of the event. And "}" tells the end of the event. So when the user clicks the button, the code written between "{" and "}" is being executed. The second line makes the ball invisible, using "_visible" property. This property can be set to "true" ("yes"), this means visible, and to "false" ("no"), this means invisible. This type of construction ( "true" and "false") is called "Boolean", which you will learn later.
Rotation
editRotation property specifies the rotation of the object in degrees. To test this property follow the steps.
Step 1
Select the Rectangle Tool in the Toolbox, draw a rectangle, double click the drawn rectangle and press F8 to convert it to symbol. When the "Convert to Symbol" dialog will appear, type "mov_box" as the name of the symbol, choose the "Movie Clip" behavior and press OK. Select the rectangle you have drawn and give "box" name to it.
Step 2
Now right click the Keyframe in Timeline window and choose "Actions" from the popup window to show "Actions" window. When the window is shown, turn on Advanced Mode and write the following:
box._rotation = 45;
Now test the movie by pressing Ctrl + Enter and you will see the result.
Quality
editProperty quality is not very important. It only changes the quality of the scene. But it doesn’t change the quality of the object, since its quality property is set. Rather it changes the quality of all the movie. For example if you write the following:
box._quality = "LOW";
then this will decrease not only of the quality of box object, but also the qualities of all other objects.
Name
editThis property changes or reads the name of the object. To understand how to use this property let's test it. We will use the example which we used when we were learning "Rotation" property. Right click the keyframe in Timeline window to see the "Actions" window. Now add the following lines to the code:
box._name = "box2";
box._rotation = 45;
Test the movie and you will notice that nothing has changed. Why? Because you have changed the name of the "box" to "box2", so now the object with the name "box" doesn’t exist. But if you only replace the word "box" in the second line to "box2" and it will look like "box2._rotation = 45; ", then, by testing the movie you will see that the box is rotated.
Alpha
editAlpha gives the object transparency. If alpha value is set to 0, then the object is completely invisible. If the value is set to 100, then the object is completely visible. You can set alpha value to your object both in design time by choosing "Alpha" in "Color" combo box in the Property window and in runtime, by using ActionScript. To test this add the following line to the previous example.
box._alpha = 30;
The following line will make the box transparent.
PartI/Chapter 2
Operators (1)
editIn this chapter you will learn all of the operators which are used in ActionScript.
Usual operators
Operator | Description |
---|---|
" " | Text. Example: "hello", "hi", "button" |
() | performs a grouping operation on one or more parameters, or surrounds one or more parameters and passes them as parameters to a function outside the parentheses. Example: trace ("hello!!!"); |
Arithmetic operators
Operator | Description |
---|---|
- |
used for negating or subtracting. Example: a = 5 – 2; b = a -1; |
% | calculates the remainder of expression1 divided by expression2. Example trace (12% 5); returns 2 |
* | multiplies two numerical expressions. Example: a = 5 * 5; b = a * 2; |
/ | divides expression1 by expression2. Example: a = 20 / 4; b = a / 5; |
+ |
adds numeric expressions or concatenates (combines) strings. Example: a = 5 + 5; b = "hel" + "lo"; |
Assignment operators
Operator | Description |
---|---|
-= |
assigns expression1 the value of expression1 -expression2. a = 5; b = 2; a -= b instead of a = a - b; |
%= |
assigns expression1 the value of expression1% expression2. a = 12; b = 5; a%=b instead of a=a % b; |
*= | assigns expression1 the value of expression1 *expression2. a = 2; b = 4; a *= b instead of a = a * b; |
/= |
assigns expression1 the value of expression1/expression2. a = 4; b = 2; a /= b instead of a = a / b; |
+= |
assigns expression1 the value of expression1 + expression2. a = 3; b = 2; a += b instead of a=a + b; |
= |
assigns the type of expression2 to expression1. b = "hello"; z = b; c = z + "!!!"; |
Other operators are discussed later after chapter Data types.
Comments
editComments 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. There are two types of using comments. The first one is a one line comment and the other one: multi-line comment. For implementing one line comment just put "//" followed by your comment at the end of the line, if the line is not empty, and at the beginning of the line if it is empty. Examples:
This example demonstrates the use of comment at the end of the line
box._rotation = 45; //This rotates "box" object by 45 degrees
This example demonstrates the use of comment in an empty line
//This is just a comment
This example demonstrates the use of comment in an empty line in work
//Rotating "box" object by 45 degrees
box._rotation = 45;
Note that you cannot use any type of comment inside the script! For implementing a multi-line comment you must just put your comment between symbols "/*" and "*/" (Note that all rules applied for one line comment are also applied for multi-line comment). Examples:
/* We are now going to
rotate our box by 45
degrees */
box._rotation = 45;
box._rotation = 45; /* Rotating our box by 45 degrees */
/* Rotating our box by 45 degrees */
box._rotation = 45;
// Box has been rotated!
You cannot use comments like this:
box._rotation = 4/*just comment*/5;
This is a syntax error.
PartI/Chapter 3
Data types
editIn this chapter we will learn how to use variables and data types. First lets talk about variables. Variables are very useful to keep data in them, but each variable has its data type. Below are listed data types available in ActionScript:
Data Type | Description |
---|---|
String | This is a text variable. For example if you set its value to "5" and then add 6 to it, the result will be "56" not "11". To have the result "11" you will have to use Number. |
Number | This is a number variable. If you want to add some numbers, then you must use this data type. But for example if you have a number variable which’s value is 5 and you add a string variable "5" to it then the result will be "55" not 10. |
Boolean | As we discussed in the previous chapters, Boolean is a data type which has only two values: true and false. |
Date | This is a date variable. You can keep your date in it or you can just access the current date (time, hours, minutes, year, month…). |
Array | This is a collection variable. You can keep on one but as much values as you want. |
Object | This data type is used to create or use objects. |
General concepts and difference between Number and String data types
editLets write a small program to test this data types. Create a new movie and open Frame 1’s actions by right clicking the first frame in the Timeline window and choosing "Actions". In the Script pane type the following:
1. var num = new Number();
2. var txt = new String();
3.
4. num = 5;
5. txt = "hi";
6.
7. trace(num);
8. trace(txt);
The first line declares a new number variable: "num". The word "var" is used to declare variables. After "var" must follow the variable’s name, in our case it is "num". You can declare variables without assigning any data type. For example:
var i;
"var i;" means that we declare i variable without assigning any data type. In in our code "var num = new Number();" we declare "num" variable and assign "Number" data type. This means that "num" variable can keep and work with only numbers. The word "Number" and other data types must be followed with the brackets. If there is nothing written in the brackets then the value of the variable is set to its default. In our case, our num variable is 0 at first. If you delete the line 4, you will notice, that the traced value is 0. In line 2 we declare another variable "txt" but this time we assign it "String" data type. This means that "txt" variable will not be able to calculate or simply work with numbers. In line 4 we set the value of "num" to 5 and in line 5 we set the "txt" value to "hi". And finally when we trace these two variables in lines 7 and 8 we saw the output:
Now lets make a test.
1. var num1 = new Number(20);
2. var txt1 = new String("Hello");
3. var num2 = new Number(5);
4. var txt2 = new String("...");
5.
6. num1 += num2;
7. txt1 += txt2;
8.
9. trace(num1);
10. trace(txt1);
In first 4 lines we declare 2 number and 2 string variables and set their values. In lines 6 and 7 we calculate two same data type variables with each other and keep the result in the first variable. For example in line 6 "num1" variable is 20, by using "+=" operator we add "num1" "num2". We can replace the line with "num1 = num1 + num2". This is the same. If we add 5 to 20 the result will be 25. In line 7 we combine two strings with each other. The result is kept in "txt1" as in "Hello…". Now test the movie by pressing Ctrl + Enter and you will see the results 25 and "Hello…". Now lets test the same example but only change lines 6 and 7:
6. num1 += txt2;
7. txt1 += num2;
What do you think will happen? Test the movie and see. The variable "num1" will become a string, because the result will be:
PartII/Chapter 4
Conditions/Loops (part 1)
editConditions and loops are one of the most important things not only in ActionScript but also in all programming languages, because they are used everywhere. For understanding these conditions lets discuss each of them one by one.
If, else if, elseedit“if” is used to compare two or more expressions. For example you have an “Input Text” and a button. You want to check if the value of “Input Text” equals “hello”. To do that you must use “if”. The use of “if” is the following: if ( <condition> ) {
//here goes your code
}
The code in “if” will be executed when the condition which you write is true. But for example you wrote a condition which was false, and you want to know about it. In this case you can use “else”. if ( <condition> ) {
//here goes your code
} else {
//here goes your code
}
But before using any condition you must know comparison and logical operators. |
Operators (part 2)
editComparison operators
Operator | Description |
---|---|
!= |
This operator returns true if two expressions are the same, and false if they aren’t. If their data types are different, then they are converted. For example “5” != 5 returns false thou “5” is a string and 5 is a number. |
!== |
This operator is the same as “!=” the only difference is that data types are not converted. |
< |
Compares two expressions and determines whether expression1 is less than expression2. If so, the operator returns true |
<= |
Compares two expressions and determines whether expression1 is less than or equal to expression2 ; if it is, the operator returns true |
== |
This operator checks whether expression1 equals expression2, returns true if so and if data types are not the same, then they are converted. |
=== |
This operator is the same as “==” but in “===” data types are not converted. |
> |
Compares two expressions and determines whether expression1 is greater than expression2 and returns true if so. |
>= |
Compares two expressions and determines whether expression1 is greater than or equal to expression2 and if so it returns true. |
Logical operators
Operator | Description |
---|---|
! |
Inverts the Boolean value of a variable or expression. |
&& |
The operator “&&” means “and”. For example you can join two conditions with it. |
|| |
The operator “||” means “or”. It can be used for joining two conditions. |
Miscellaneous operators
Operator | Description |
---|---|
-- |
This operator subtracts 1 from the expression. For example you have “a” variable and want to decrease its’ value by one. Instead of writing “a-=1” or “a=a-1” you can write “a--“. |
?: |
This operator is the same as “if” condition. The following example will demonstrate how it works:
var x = new Number(5);
var y = new Number(10);
var z = new Number();
z = (x < y) ? x: y;
The last line means that if “x<y” then “z=x” else “z=y”. You can write the same using “if”. if (x < y) {
z = x;
} else {
z = y;
}
|
++ |
This operator adds 1 to the expression. For example you have “a” variable and want to increase its’ value by one. Instead of writing “a+=1” or “a=a+1” you can write “a++“. |
instanceof |
Discussed later |
typeof |
The “typeof” operator evaluates expression; the result is a string specifying whether the expression is a string, movie clip, object, or function. For example you have a button named “mybutton”. If you write this code:
trace(typeof(mybutton)); then the traced value will be “button”. If the object is Movie Clip then the return value is “movieclip”, if it is a string the return value is “string”. |
void |
Discussed later |
Now when you know these operators we can continue learning conditions and writing new programs.
Conditions/Loops (part 2)
editLets write a program which will check if the values of two Input Texts are the same. First of all create two Input Text and set first ones var to “input1” and the second ones to “input2”. Then add a button and set its name to “button”. Add the following lines to the actions of “button1”:
1. on (release) {
2. if (input1 == input2) {
3. trace(“YES”);
4. } else {
5. trace(“NO”);
6. }
7. }
In line 2 we check if input1 equals input2 using “if” and operator “==” (Note: don’t confuse “=” with “==” because they are different operators. “=” assigns value to the variable, but “==” only checks two expressions. For example if you have “if” and you want to check if any variable “a” equals “hello” then you must write “ a==”hello” ” in the condition. If you write “ a=”hello” “ then a will become “hello”.) and if so then we trace “YES” else we trace “NO”. But now imagine another situation. You have an Input Text and a button and when the user type his/her name in the Input Text and clicks the button you want to trace different values. To solve this you must add the following code to the button:
1. on (release) {
2. if (input1 == “Jane”) {
3. trace(“Hello Jane!!!”);
4. } else if (input1 == “Ben”) {
5. trace(“Hello Ben!!!”);
6. } else if (input1 == “John”) {
7. trace(“Hello John!!!”);
8. } else {
9. trace(“Hello unknown!!!”);
10. }
11. }
If you want you can write a simple program just for you. You can create two Input Texts one button, a Dynamic Text (that will show the status) and write a code to determine if the user who want enter your program is member or not. This little program will be your security, keeping other people away. Below is shown a little fragment of the button’s actions:
1. on (release) {
2. if (UserName == “user1” && Password == “password1”) {
3. //here goes your code
4. } else if (UserName == “user2” && Password == “password2”) {
5. //here goes your code
6. } else {
7. Status = “Invalid Details!”;
8. }
9. }
UserName is the “var” property of the first Input Text Password is the “var” property of the second Input Text Status is the “var” property of the Dynamic Text
For
edit“For” is used to repeat the code for several times. Below is shown the use of “For”:
for ( <init>; <condition>; <next> ) {
//here goes your code
}
Now I will bring you example where you need to use “For”. For example you want to add all numbers from 1 to 10 (1+2+3+4+…+10). For doing it you have to write the following code:
1. var i = new Number(); 2. i += 1; 3. i += 2; 4. i += 3; 5. i += 4; 6. i += 5; 7. i += 6; 8. i += 7; 9. i += 8; 10. i += 9; 11. i += 10;
(or if you are too smart)
1. var i = new Number();
2. i = 1+2+3+4+5+6+7+8+9+10;
But, anyway, it’s boring to write such a code. Instead you can use “For” and repeat the code for 10 times:
1. var i = new Number();
2. for ( e = 1; e <= 10; e++) {
3. i += e;
4. }
<syntaxhighlight>
In the first line we declare “i” number variable. In line 2 we begin our “For”. “e = 1” is the <init> part. In the init part you assign value to the variable. In our case we assign “1” to variable “e”. Now you must ask why I use the word “variable” with “e”. Because when you init the value Flash automatically makes “e” a number variable. If you declare “e” as a number variable in the beginning of the code there will be no problem. You can write the following example like this:
<syntaxhighlight lang="actionscript3">
1. var i = new Number();
2. var e = new Number();
3. for ( e = 1; e <= 10; e++) {
4. i += e;
5. }
The second part of “For” <condition> tells Flash how much to repeat the action. In our case we wrote to repeat the action while e is less than or equal to 10. So when “e” becomes 11 it will stop repeating the action. In the third part of “For” is <next> you must tell Flash how to change the value of the variable each time it repeats the action. In our case we wrote “e++”. This means that each time Flash repeats the action it will increment e by one. In the actions of “For” (line 4) we wrote “i += e;”. This means that we will add “e” to “i” each time the action repeats. So this small code will give the sum of numbers from 1 to 10. You can trace the value of “i” at the end of the code to see its value. It must be “55”.
1. var i = new Number();
2. var e = new Number();
3. for ( e = 1; e <= 10; e+=2) {
4. i += e;
5. }
This example does the same as the previous one, but this time we increment the value of “e” by 2, not by one, as in the previous example. So our example will count the sum of the following numbers: “1, 3, 5, 7, 9”.
For .. In
edit“For .. In” is used to loop through the properties or objects of the object you specify. The following is the structure of the statement:
for ( <variableIterant> in <object> ) {
//here goes your code
}
Now lets understand what, where and how can this statement be used. For example, if you want to get the list of objects in “_root” object you must write the following:
1. var e = new String(“Hello!!!”);
2. for (obj in _root) {
3. trace(obj);
4. }
If you write this code in the actions of the frame and run it, the output value will be:
The first line of the code declares a new string variable named “e”. Then the program loops though each element in “_root” object and traces its name. You already know that each local variable declared in timeline is an element of “_root” object like “e”, but what is “$version”? “$version” is a built-in string variable which keeps the name and the version of the operating system the movie is run at.