Chapter ii(coding)

Preview:

Citation preview

Getting Started with ActionScript

What Scripts Can Do• Animation You don't need ActionScript to create animation in Flash. But scripting can help

to create some complex animation. For instance, a ball can bounce around the screen in a seemingly endless path with ActionScript. It can even obey the laws of physics, being pulled down by gravity. If you were to animate such a thing without ActionScript, you might need thousands of frames. But a script can do it in one frame.

• Navigation Instead of the movie moving forward at a constant pace, you can pause it at a menu of choice and let the user decide where to go next.

• User Input You can ask the user questions and use that information in the movie or send it to a server. A Flash movie with some ActionScript can be a better way to do a Web form. Or, the movie itself can use the information to customize the user's experience.

• Get Data A script can interact with the server in the opposite direction, too. You can get up-to-date information and present it to the user.

• Calculations ActionScript can take numbers and perform calculations with them. It can predict a mortgage payment or add up the cost of items in a shopping cart.

• Graphic Alterations Scripts can be written to alter the size, angle of rotation, or even the color of movie clips in your movie. You can even duplicate or remove items from the screen.

• Examine the Environment You can use ActionScript to examine the playback environment of a Flash movie. You can find out what time and date it is and what location the movie is being played from.

• Play Sounds ActionScript is a good alternative to the Flash timeline for playing sounds. You can even control the balance and volume of a sound.

A Brief History of ActionScript in Flash

• ActionScript 1 with Flash 3• Flash MX 2004 (7) ActionScript 2.0 (class

document)• Flash CS3 (9) with ActionScript 3.0 (oop)

Comments• The comments within the code are necessary when we

want to specify the role and functions of certain variables or instructions, for easy understanding of the script later .

• Single-line comment:– // This is a comment; it’s ignored by the computer.

• Multiline comments:– /*

This might be a really long description, perhaps describing what computer.

*/

Constructing ActionScript• trace(“I have love broken.”);• trace(5 + 5); // Displays: 10• trace(“5” + 5); // Displays: 55• trace(Boolean(0)); // Displays: false• trace(Boolean(1)); // Displays: true• trace(Number(“24”));• trace(Boolean(“true”)); // Displays: true• trace(Boolean(“false”)); // Displays: true

The "? :" conditional operator • used to determine the execution of a function or another, depending

on the result of a logical expression .– variable = (condition) ? val1_true : val2_false; – EX:var num:Number = 0.3;// set "str" variable depending on the value of "num"var str:String = (num > 5) ? 'www.marplo.net' : 'www.coursesweb.net';trace(str); // www.marplo.net/* Equivalent with: if(num > 5) { var str:String = 'www.marplo.net'; } else { var str:String = 'www.coursesweb.net'; }*/

Constants• Constants are a special kind of variable, store a

value that never changes during the course of the program .– const CONSTANT_NAME:DataType = value;

• const BROTHER:String = 'Victor';const BROTHER_AGE:uint = 33;trace(BROTHER+ ' - '+ BROTHER_AGE);

•EX1:var myString="ka";trace(myString == "ka");•EX2:var a = 7; trace(a != 9);•EX3:// declare a variable that would hold a numerical value, and set this value to 78 var num:Number = 78; // create a variable that would hold a string value, and then set a value var str:String; str = "www.coursesweb.net"; •EX4:// declare numerical variable var num:Number = 78; // declare another numerical variable, and assign it the value of "num" var num2:Number = num; // change the value of "num" variable num = 89;

Data Type1. String: a textual value.2. Numeric: three specific data types for numeric data:

1. int: an integer (a whole number without a fraction)2. uint: an “unsigned” integer, meaning a whole number that can’t be negative

3. Boolean: a true-or-false value, such as whether a switch is on or whether two values are equal.

Variables• Variables are elements that store data. • must use the var keyword. • var variableName:Datatype;

– var myVariableName; // var required – var x:Number; // variable x contains number values – var anyValue:*; // variable can have any type – var untyped:*; // (or no typing) undefined – var boolean:Boolean; // false – var number:Number; // NaN – var a:int, b:int, c:uint;– var unsignedInteger:uint; // 0 – var string:String; // null – var object:Object; // null – var birthday:Date = new Date(2006, 7, 9);– var someNumber:Number = 6.33;– var someNumber:Number = new Number(6.33);

Escape sequence

Working with objects

1. Properties- represents one of the pieces of data that are bundled together in an object.- Properties - are characteristics that define an object.

- For example, "color" can be property of a DVD player. - square.x = 100; square.rotation = triangle.rotation;

2. Methods- action that can be performed by an object- are actions that can be performed by an object.

For example, Play, and Pause are methods of a DVD player. - shortFilm.play(); shortFilm.stop(); shortFilm.gotoAndStop(1);- var numericData:Number = 9;

var textData:String = numericData.toString();

3. Events- is the action of an application or user, such as a mouse click, that triggers an action related to an object. - a series of instructions that the computer carries out step-by-step and things that

happen that ActionScript is aware of and can respond to.- function eventResponse(eventObject:EventType):void{

// Actions performed in response to the event go here.}eventSource.addEventListener(EventType.EVENT_NAME, eventResponse);

Ex1:function updateOutput(event:TextEvent):void{var pressedKey:String = event.text;outputText.text = "You typed: " + pressedKey;}entryText.addEventListener(TextEvent.TEXT_INPUT, updateOutput);

Ex2:function gotoAdobeSite(event:MouseEvent):void{var adobeURL:URLRequest = new URLRequest("http://www.adobe.com/");navigateToURL(adobeURL);}linkButton.addEventListener(MouseEvent.CLICK, gotoAdobeSite);

User Interface

Ascii() String Code27 .(esc) 278 .(backspace) 80 (capslock) 200 (shift) 16

(alt) 180 (ctrl) 1713 (enter) 1332 (space) 32function keys0 (F1) 1120 (F2) 1130 (F3) 1140 (F4) 1150 (F5) 1160 (F6) 117

0 (F7) 118

0 (F8) 1190 (F9) 1200 (F10) 1210 (F11) 1220 (F12) 123letters and other main keybd w/shift key on126 ~ 19

233 ! 4964 @ 5035 # 5136 $ 5237 % 5394 ^ 5438 & 5542 * 5640 ( 5741 ) 4895 _ 18

943 + 18

7124 | 22

081 Q 8187 W 8769 E 6982 R 8284 T 8489 Y 8985 U 8573 I 7379 O 7980 P 80123 { 21

9125 } 22

165 A 6583 S 8368 D 6870 F 7071 G 7172 H 7274 J 7475 K 7576 L 7658 : 18

634 " 22

290 Z 9088 X 8867 C 6786 V 8666 B 6678 N 7877 M 7760 < 18

862 > 19

063 ? 19

1letters and other main keybd, no shift96 ` 19

249 1 4950 2 5051 3 5152 4 5253 5 5354 6 5455 7 5556 8 5657 9 5748 0 4845 - 18

961 = 18

792 \ 22

0113 q 81119 w 87101 e 69114 r 82116 t 84121 y 89117 u 85105 i 73111 o 79112 p 8091 [ 21

993 ] 22

197 a 65115 s 83100 d 68102 f 70103 g 71104 h 72106 j 74107 k 75108 l 7659 ; 18

639 ' 22

2122 z 90120 x 8899 c 67118 v 8698 b 66110 n 78109 m 7744 , 18

846 . 19

047 / 19

1keypad keys w/numlock on47 / 11142 * 10645 - 10955 7 10356 8 10457 9 10552 4 10053 5 10154 6 10249 1 9750 2 9851 3 9948 0 9646 . 11013 1343 + 107keypad keys w/numlock off47 / 11142 * 10645 - 1090 (Home) 360 (up arrow) 380 (PgUp) 330 (left arrow) 370 120 (right arrow) 390 (End) 350 (down arrow) 400 (PgDown) 340 (Ins) 45127 (Del)� 4613 (Enter) 1343 + 107middlekeys0 (ScrollLock) 1450 (Pause) 190 (Ins) 450 (Home) 360 (PageUp) 33127 (Delete)� 460 (End) 350 (PageDown) 34arrowkeys0 (left) 370 (up) 380 (down) 400 (right) 39

MouseEvent - Events for Mouse•CLICK - is triggered when the user presses and releases the main mouse button over an object in the Flash presentation•DOUBLE_CLICK - is triggered when a double-click is executed on the recorded object. This object must have the doubleClickEnabled property set to true•MOUSE_DOWN - detects the moment when the left mouse button is pressed (without being necessary to release the click)•MOUSE_UP - executes the event when the click is released•MOUSE_MOVE - the event is triggered each time the mouse pointer is moved over an objects•MOUSE_OUT - the event is executed when the mouse leaves the objects area or the area of any of its "child elements"•MOUSE_OVER - is triggered when the mouse enters the area of the monitored object or of any "child element"•MOUSE_WHEEL - event is dispatched when a mouse wheel is spun over a monitored object in the Flash Player•ROLL_OUT - it's similar to MOUSE-OUT, the difference is that the event is triggered only when the mouse completely leaves the object's area, while, the MOUSE_OUT event is thrown each time the mouse leaves the area of any child object of the display object container.•ROLL_OVER - is similar to MOUSE-OVER, the difference is that the event is triggered when the mouse enters the objects area, while, the MOUSE_OVER event is thrown each time the mouse enters the area of any children of the monitored object

testClip.width = latura; testClip.height = latura;

Numbers and Math• NaN - Not a number

– var num1:Number;var num2:Number = 0/0;trace(num1); // NaNtrace(num2); // NaN

– var num:Number;trace(num); // NaNtrace(isNaN(num)); // trueif(isNaN(num)) { num = 78;}trace(num); // 78

• Methods and Constants of the Number object– var nr:Number = 123456789;

trace(nr.toExponential(2)); // 1.23e+8– var nr:Number = 12.3456789;

trace(nr.toFixed(3)); // 12.346– var nr1:Number = 12.3456789; – trace(nr1.toPrecision(4)); // 12.35 – var nr2:Number = 123400000; – trace(nr2.toPrecision(4)); // 1.234e+8

– var nr:int = 7;var str:String = '8';trace(nr.toString()+ str); // 78 (or String(nr)+ str )

– var nr:int = 7;var str:String = '8';trace(nr+ Number(str)); // 15

– trace(int.MAX_VALUE); // 2147483647trace(uint.MAX_VALUE); // 4294967295trace(Number.MAX_VALUE); // 1.79769313486231e+308

– trace(int.MIN_VALUE); // -2147483648trace(uint.MIN_VALUE); // 0trace(Number.MIN_VALUE); // 4.9406564584124654e-324

– var nr:Number = -7/0;trace(); // -Infinitytrace(nr == Number.NEGATIVE_INFINITY); // true

– var nr:Number = 8/0;trace(); // Infinitytrace(nr == Number.POSITIVE_INFINITY); // true

• Math class– var nr:Number = Math.pow(3, 4); // 3 raised to power 4

var nr2:Number = Math.random(); // get a random value between 0 and 1

String Object•var str:String = "Any text";trace(str.length); // 8•var str:String = "Some text";trace(str.charAt(3)); // e•var str:String = "Un sir";trace(str.charCodeAt(3)); // 115•var str:String = "Test ";trace(str.concat('str1', ' str2')); // Test str1 str2•trace(String.fromCharCode(115, 118)); // sv •var str:String = "Tutorials";trace(str.indexOf('tor')); // 2•var str:String = "Tutorials, in online courses";trace(str.lastIndexOf('in')); // 17•var str:String = "Tutorials, tutor, courses";var exp:RegExp = /tu[a-z]+/gi;trace(str.match(exp)); // Tutorials,tutor •var str:String = "Tutorials, tutor, courses";var exp:RegExp = /tu[a-z]+/gi;trace(str.replace(exp, 'Lessons')); // Lessons, Lessons, cursuri

•var str:String = "Tutorials, tutor, courses"; var exp:RegExp = /r[is]/i; trace(str.search(exp)); // 4 •var str:String = "ActionScript free online"; trace(str.slice(13, 17)); // free •var str:String = "Free-online-ActionScript"; trace(str.split('-')); // Free,online,ActionScript •var str:String = "http://www.marplo.net"; trace(str.substr(11, 6)); // marplo •var str:String = "Tutorials, Courses ONLINE"; trace(str.toLowerCase()); // tutorials, courses online •var str:String = "Tutorials, Courses ONLINE"; trace(str.toLowerCase()); // TUTORIALS, COURSES ONLINE •var nr:int = 7; var str:String = '8'; trace(nr.toString()+ str); // 78 (or String(nr)+ str ) •var nr:int = 7; var str:String = '8'; trace(nr+ Number(str)); // 15

Date and Time in ActionScript• var dat:Date = new Date();

trace(dat); // Tue Nov 9 09:58:18 GMT+0200 2010• var dat:Date = new Date(2010, 0, 15);

trace(dat); // Fri Jan 15 00:00:00 GMT+0200 2010• var dat2:Date = new Date(2010, 11, 15, 18, 22, 32, 88);

trace(dat2); // Wed Dec 15 18:22:32 GMT+0200 2010• var dat:Date = new Date();

var hour:int = dat.getHours(); // or dat.hours;• var day:int = dat.date; // or dat.getDate();

trace(day); // 19trace(hour); // 8

• var dat:Date = new Date('Sun Jan 28 2007 14:16:12');dat.date = 11; // or dat.setDate(11);dat.setHours(8); // or dat.hours = 8;trace(dat); // Thu Jan 11 08:16:12 GMT+0200 2007

Flow control1. IF:

o if..elseif (x > 20){trace("x is > 20");}else{trace("x is <= 20");}

o if..else ifif (x > 20)

{trace("x is > 20");}else if (x < 0){trace("x is negative");}

EX:var a=20;if (a == 7) { gotoAndPlay(10); } else if (a == 8) { gotoAndPlay(15) {} else if (a == 13) { gotoAndPlay(20); } else { gotoAndPlay(25); }

EX1:var a=7,b=4;if ((a >= 7) and (b <=15)) { gotoAndPlay(20); } EX2:if ((a == 7) or (b == 15)) { gotoAndPlay(20); } EX3:var num:Number = 8;if(num > 7) { trace('Condition true');}// Condition true

EX:var day:String = 'Monday';if(day=='Sunday') { trace('Stay home');}else { trace('Go to work');}// Go to workEX:var day:String = 'Monday';

if(day=='duminica') { trace('Stay home');}else if(day=='Monday') { trace('Go to grandparents');}else if(day=='Saturday') { trace('Sport');}else { trace('Go to work');}// Go to grandparents

2. Switch statementswitch (variable) { case value1: code to execute if variable = value1 break; case value2: code to execute if variable = value2 break; case value3: code to execute if variable = value3 break; default : code to execute if none of the other cases match}

var day:String = 'Tuesday';

switch(day) { case 'Sunday': trace('Stay home'); break; case 'Monday': trace('Go to grandparents'); break; case 'Tuesday': trace('A walk in the garden'); break; case 'Saturday': trace('Sport'); break; default: trace('Go to work');}

var someDate:Date = new Date();var dayNum:uint = someDate.getDay();switch(dayNum){case 0:trace("Sunday");break;case 1:trace("Monday");break;case 2:trace("Tuesday");break;case 3:trace("Wednesday");break;case 4:trace("Thursday");break;

case 5:trace("Friday");break;case 6:trace("Saturday");break;default:trace("Out of range");break;}

2. Looping– For

var i:int;for (i = 0; i < 5; i++){trace(i);}

– for..invar myArray:Array = ["one", "two", "three"];for (var i:String in myArray){trace(myArray[i]);}

– for each..invar myArray:Array = ["one", "two", "three"];

for each (var item in myArray){trace(item);}

– Whilevar i:int = 0;while (i < 5){trace(i);i++;}

– do..whilevar i:int = 5;do{trace(i);i++;} while (i < 5);

EX1:var total:int = 1;// executes a for loop 4 timesfor(var i:int=0; i<4; i++){ // doubles the value of "total" and output it total *= 2; trace(total);}

EX2:var total:int = 1;

// executes a for loop 4 timesfor(var i:int=0; i<4; i++){ // ends the loop when i=2 if(i==2) { break; }

// double the value of "total" and output it total *= 2; trace(total);}

Break

• break is an instruction that allows you to stop processing a loop (or "switch" conditional) .– EX:var total:int = 1;for(var i:int=0; i<4; i++){ total *= 2; if(total==8) break; // ends completely this loop trace('i='+ i+ ' - total='+ total);}

Continue

• The continue instruction skips the remaining statements in the current loop and begins the next iteration at the top of the loop .– EX:

var total:int = 1;for(var i:int=0; i<4; i++){ total *= 2; // skip other actions in the current iteration when total==4 or

total==8 if(total==4 || total==8) continue;

trace('i='+ i+ ' - total='+ total);}

Creating Functions• A function is a set of instructions (a block of code) that are executed

only when you access the functions. • There are two general kind of functions:

– predefined - which are included in the programming language (e.g. trace(), addChild(), etc.)

– created by programmer:• that returns a value (uses the "return" statement)• not returns a value

– Formed:function functionName(param1:DataType, param2:DataType, ...):fDataType { // code to execute (the function body) }

EX0:function getMsg(msg:String) { trace(msg); } var site:String = 'www.coursesweb.net'; // define a String variable getMsg('Welcome to');Ex1:function getText(st:String){

txt1.text=st.toString();}function testMovie(event:MouseEvent):void{

getText("Hello, how are you?");}bt1.addEventListener(MouseEvent.CLICK, testMovie)Ex2:function getText(st:String):String{

return st;}function testMovie(event:MouseEvent):void{

txt1.text=getText("Hello, how are you?");}bt1.addEventListener(MouseEvent.CLICK, testMovie)

Functions - Advanced Use• Setting parameters with default value

function sayHy(name:String = 'You') { trace('Nice to meet '+ name);

}sayHy('Marius'); // displays: Nice to meet MariussayHy(); // displays: Nice to meet You

• Using the rest parameter (...)function testF2(... nums):void

{ // declare a variable which will be used to store the sum of the values passed in arguments var latura:Number = 0; // define a "for each..in" to access each value stored in "nums" Array for each (var num:Number in nums) { latura += num; // add the current value to "latura } // uses the variable, "latura" to set the 'width' and 'height' for "testClip" testClip.width = latura; testClip.height = latura;}testF2(8, 20, 40, 50);

Assign function to a variable// define a function with 3 parameters in a variablevar vrF:Function = function (obj:MovieClip, sx:Number, sy:Number):* { // "obj" must be the instance of a MivieClip // define "scaleX" and "scaleY" properties for "obj obj.scaleX = sx; obj.scaleY = sy; }

// call the function, passing the 'testClip' instance for the "obj" parametervrF(testClip, 2.5, 1.4);

Variables and Functionsvar ext_vr:int = 18; // variable created outside any function// define a function which use the "ext_vr" variablefunction oFunctie():Number{var in_vr:Number = 7; // add the value of the external variable "ext_vr" to the local variable in_vr += ext_vr; return in_vr; // return the values of "in_vr"}trace(oFunctie()); // displays in Output the value returned by the function (25)

Recursive Functions// define a recursive functionfunction factorial(n:uint):uint{ // if n>0, multiply 'n' auto-calling function if(n > 0) { return (n * factorial(n-1)); } else { return 1; } // return 1 when n>0 is false}// store in a variable the value returned by factorial(8)var fact:uint = factorial(8);trace(fact); // Output: 40320

Casting to int, uint, and Number• var myBoolean:Boolean = true;• var myUINT:uint = uint(myBoolean);• var myINT:int = int(myBoolean);• var myNum:Number = Number(myBoolean);• trace(myUINT, myINT, myNum); // 1 1 1• myBoolean = false;• myUINT = uint(myBoolean);• myINT = int(myBoolean);• myNum = Number(myBoolean);• trace(myUINT, myINT, myNum); // 0 0 0

Array

• Arrays are variables that store multiple values in a single variable name. So, an Array is a variable with an ordered list of values.

• var myStrings:Array = new Array(["alpha", "beta", "gamma"]);• var myNums:Array = new Array([1,2,3,5,8]);• var myStrings:Array = ["alpha", "beta", "gamma"];• var myNums:Array = [1,2,3,5,8];

EX:var m_ar:Array = ['web site', 'www.coursesweb.net', 78];// get the second item (with index 1)trace(m_ar[1]); // Output: www.coursesweb.netEX:var m_ar:Array = ['web site', 'www.coursesweb.net', 78];

// define a variable to be used for indexvar i:uint = 2;

// create a variable which use an array item for its valuevar test = 4 + m_ar[i];

trace(test); // Output: 82EX:var m_ar:Array = ['web site', 'www.coursesweb.net', 78];// changes the value of the first elementm_ar[0] = 'tutorials';// use "trace(m_ar)" to check the Array valuestrace(m_ar); // tutorials,www.coursesweb.net,78// adds a new element in "m_ar" (fourth, with index 3)m_ar[3] = 'ActionScript';// use "trace(m_ar)" to check the Array valuestrace(m_ar); // tutorials,www.coursesweb.net,78,ActionScript

EX:var m_ar:Array = ('web site', 'www.coursesweb.net', 78);var nrel:int = m_ar.length;trace(nrel); // 3m_ar[5] = 'www.marplo.net';nrel = m_ar.length;trace(nrel); // 6trace(m_ar); // web site,www.coursesweb.net,78,,,www.marplo.netEX:var m_ar:Array = ('web site', 78, 'www.marplo.net‘);

// set a number of 8 items in "m_ar"m_ar.length = 8;var nrel:int = m_ar.length;trace(nrel); // 8m_ar.length = 2;nrel = m_ar.length;trace(nrel); // 2trace(m_ar); // web site,78

var v:Array=new Array([1,2,3,4,5],[6,7,8,9,0]);trace(v[1][0]);

http://www.republicofcode.com/tutorials/flash/basicwebsite/

Control with sound

Recommended