Actionscript 3

anthropologistbarrenΛογισμικό & κατασκευή λογ/κού

4 Ιουλ 2012 (πριν από 4 χρόνια και 11 μήνες)

285 εμφανίσεις

Actionscript 3.0





Brief n
otes to learning the vocabulary and syntax of the latest version of Flash’s
programming language.




Variables and Data Types..............................................................
...

Page 2


Conditionals.................
............................................
.........................

Page 2


Switch...............................................................................................

Page 5


Loops...............................................................
.......
.........................

Page 6


Arrays ..............................................................................................

Page 7


Functions

.......................................................................................
..

Page
7


Arguments ......................................................................................
.
.

Page 8


Custom Objects ............................................................................
...
.

Page 9


Properties Methods and Events ............
...............
........................
....

Page 10


Object Orientated Programming ......................................................

Page 12


Event Listeners................................................................................

Page 12


Cr
eating Custom Classes.................................................................

Page 13















2



Variables and Data Types



Variable:

A container into which information may be placed for recall later.



Allows a program to remember e.g. high
-
scores.




MyVariable = 1;


Should be all one word, not start with a number, not already be a reserved
keyword.




var
myVariable:
Number
= 1;





Data type

Example

Description




Number

4.5

Any number, including floating point values (decimals)

int

-
5

Any integer or whole number

String

“hello”

Text or string of characters

Boolean

True

True or false

Array

[2, 9, 17]

More than one value in a single variable







Conditionals



How to make decisions in your code


Create a test, ask whether the con
dition is met, if it is the test evaluates to true
and an extra piece of code is executed accordingly.


If conditions are not met then an alternative course of action may be taken, or
alternatively nothing at all.









3

if


the most common form of the co
nditional, if followed by parenthesis in which the
test resides and braces in which the code resides that executes when the
statement evaluates to true.


var
a:
Number
= 1;

var
b:
String
=
“hello”
;

var
c:
Boolean
=
false
;


if (a == 1) {


trace
(
“option a”
);

}


Conditionals often make use of comparison and logic operators. Comparison
operator compares two values;


equals (==)

less than (<)

greater than or equal to (>=)


Logical operator evaluates the logic of an expression;


AND (&&)

OR (||)

NOT (!)


The follo
wing would be false and there would be no output.



if
(a == 1 && b ==
“goodbye”
) {

trace
(
“option a and b”
);

}


The following would be true and “option a or b” would be traced


if
(a == 1 || b ==
“goodbye”
) {

trace
(
“option a or b”
);

}


Also evaluat
es to true because c is not true


if
(!c ) {

trace
(
“not option c”
);

}

Not operator can be used as part of a comparison operator, when combined with
a single equals sign means “not equal to”, therefore the following will fail


4


if
(a ! = 1 ) {

trace
(
“a
does not equal 1”
);

}


More power can be added to the if statement by adding an unconditional
alternative (true no matter what). In the following the second trace will occur



if
(a ! = 1 ) {

trace
(
“a does not equal 1”
);

} else {

trace
(
“a does equal
1”
);

}



Finally by adding a conditional alternative (an additional test), the statement is
made more robust. In the following the second trace will occur



if
(a == 2 ) {

trace
(
“a does not equal 1”
);

} else if (a == 1) {

trace
(
“a does equal 1”
);

}


the if statement requires one
if
, only one optional
else
can be used and any
number of additional
else if
tests can be used. We can only ever have one result
from the structure.


Consider the following; all three results are possible, the first two beca
use they
are true the last because it is an unconditional alternative.


If
(a == 1) {


trace
(
“option a”
);

}
else if
(b ==
“hello”
) {


trace
(
“option b”
);

}
else
{


trace
(
“option other”
);

}



Only “option a” would appear in the output panel because the fi
rst truth would exit
the
if
structure. For more than one execution, use more that one conditional; the
following would output twice.



5

If
(a == 1) {


trace
(
“option a”
);

}

if
(b ==
“hello”
) {


trace
(
“option b”
);

}
else
{


trace
(
“option other”
);

}



Switch



Come into they’re own when you have long
if
structures


switch
(a) {


case
1 :


trace
(
“one”
);


break
;


case
2 :


trace
(
“two”
);


break
;


case
3 :


trace
(
“three”
);


break
;


default
:


trace
(
“other”
);


break
;

}


if you do not use the break line the n
ext instruction will execute, even if it is false,
break feature does not exit within the if then else statement.


Switch statements must have one switch and one case, an optional unconditional
alternative (default).













6

Loops


Wrap repetitive task
s in an efficient structure. Different types;


For loop

executes contents a finite number of times.


To be effective must start with an initial value


Need to test whether the limit has been exceeded.


for
(
var
i:
Number
= 0; i < 3; i++) {


trace
(
“hell
o”
);

}



for
(
var
i:
Number
= 3; i > 0; I
--
) {


trace
(
“hello”
);

}


while loop

executes as long as something remains true

(Math classes random method chooses a random number between 0 and 1)


var
num:
Number
= 0

while
(num < .5) {


num =
Math.random
();



t
race
(“num”
,
num) ;

}





// Do not attempt to execute this code!!


var
flag:
Boolean
=
true
;

while
(flag =
true
) {


trace
(
“how many times will this loop execute?”
);

}











7


Arrays


One variable that contains more than one value


Two methods for creati
ng them;


var
myArray:
Array
= [1,2,3]

var
yourArray:
Array
=
new Array
():

push
()

adds an item to the beginning of an array

pop
()

removes an item from the end of an array


var
myArray:
Array
=
new Array
()

myArray.
push
(1);

trace
(myArray);


// 1 appears i
n the ouput panel


myArray.
push
(2);


// myArray now has 2 items 1,2


trace
(myArray.
pop
())

// the pop() method removes the last item, displaying its value of 2


trace
(myArray);

// the last remaining item, 1 appears in the ouput panel


var
myArray:
Array
= [

a”,
“b”, “c”, “d”, “e”]

trace
(myArray[4])


// “e” appears in the ouput panel, why?


Functions


An indispensable part of programming, that allows us to wrap code into blocks
and execute it when needed.



To create a basic function, simply wrap it in a par
ticular syntax (defined by the
use of braces) that allows it to trigger when called by name.


function
showMesg() {


trace
(
“hello”
);

}

showMesg();

//hello


8

Arguments


Can be parsed into functions to make them more flexible.


Very local variables that have l
ife only within their own functions.


e.g. we can pass a value into our showMesg(); function



function
showMesg(msg:
String
) {


trace
(msg)

}

showMesg(
“goodbye”
);


//goodbye


We can also return a value from a function; a varied input creates a varied
output
.


function
celtofar(cel:
Number
):
Number
{


return
(9/5)*cel +32;

}

trace
(celtofar(20)
)
;


//68


function
fartocel(far:
Number
):
Number
{


return
(9/5) * (far

32);

}

var celDeg:Number = fartocel(68);

trace
(celDeg);


//20












9

Custom Objects


Create you
r own…



var
plane:
Object
=
new Object()
;

plane.pitch = 0;

plane.roll = 5;

plane.yaw = 5;


trace(plane.pitch);


// 0


function
showPlaneStatus(obj:
Object
):void {


trace
(plane.pitch);


trace
(plane.roll);


trace
(plane.yaw);

};


showPlaneStatus(plane)


// 0

// 5

// 5


void here, (in line 1 of our function showPlaneStatus) means the function returns
no value, the values are parsed into it from the original object and then traced out
when the function is called.



10

Properties Methods and Events


The basic build
ing blocks of most scripted tasks, which allow you to:



Get and set characteristics of


Issue instructions to


React to input from, many flash elements.




Properties


Similar to adjectives, describe the object being modified, or queried.

Most are read,
write, you can both get and set these values.




Methods


Similar to verbs, used to tell objects to do something, e.g. play, stop.



Events


That which triggers the actions you write.

The click of a mouse is a mouse event, which you may choose to capture,
feed
into a function and perform a task. Event handlers and event listeners are used in
AS3 coding to trap events and execute functions.



Classes


AS reference materials are often organised into classes and certain attributes of
these may be inherited.


x and y coordinates e.g. are inherited properties of an object that tell us its
location on the stage.











11

Example of using properties




Create a new file with a movie clip of a square box on the stage with an instance
name “box”



Description

Proper
ty

Syntax for setting value

Units and / or Range


Location

x, y

box
.x
= 100;


box
.y
= 100;

pixels

Scale (1)

scaleX, scaleY

box
.scaleX
= .5;

box
.scaleY
= .5
;

percent / 0
-
1

Scale (2)

width, height

box
.width
= 72;


box
.height
= 72;

pixels

Rotation

rota
tion

box
.rotation
= 45;


degrees 0/360

Transparency

alpha

box
.alpha
= .5;

percent / 0
-
1

Visibility

visible

box
.visible
=
false
;


boolean





What do the following do?


trace
(box.
alpha
);


var
bAlpha:
Number
= box.
alpha;


box.
rotation
+= 20;



12

Using Event
Listeners



Write a function, tell the event listener to call that function when the event occurs
and tie it all together with the
addEventListener()
method



In the following example the button is called
rotate_right_btn
and the function it
should execute
is
onRotateRight()


rotate_right_btn.
addEventListener
(
MouseEvent.MOUSE_UP,
onRotateRight);


function
onRotateRight(evt:
MouseEvent
):
void
{



box.
rotation
+= 20;

}


line 1 starts with the button instance name and then adds the
addEventListener()
method.


T
his requires two mandatory parameters;

1)

The event class for which you are listening and the constant of the class to
which you are listening.

2)

The function that should be called when the event is received.


The argument in Listener functions is required, in
the example here it is arbitrarily
named evt and receives information about the element that triggered the event



OOP


Benefits include;


Classes

collections of related functions and variables, gathered together to
facilitate one or more specific goals
, the foundation of OOP. Bring together
related functions (called methods in classes) and variables (called properties in
classes).


Inheritance

a way to add functionality to a feature set without reinventing the
wheel, create subclasses without writing
new classes.


Composition

collect related classes together, classes do not inherit
characteristics, but are made to work together productively.


Encapsulation

isolates, black
-
boxes, those elements not necessary for external
purposes.




13

Creating custom
classes


Document class

does all the work of instantiating the class for you and can be
used as a timeline replacement. Create the class below in a new AS3 file, not an
fla. document. In the properties inspector of your associated fla file add the name
of the class, the name of the AS3 file is not relevant.


1

package
{

2

3


import flash
.
display
.
MovieClip
;

4

5


public class
Main
extends MovieClip
{

6

7



public function
Main() {

8




trace
(
“Flash”
);

9



}

10


11


}

12

}



A package is a wrapper for you
r class


For ease of use, you should place all your classes in the same directory as your
fla. file.



Line 3 is a compiler directive that instructs the flash compiler to include all the
properties, methods, and events in the classes or packages listed whe
n
compiling your movie.


Lines 5 to 11 declare the class


public
is called the namespace and makes the class available to the rest of any
given project


Name of class
Main


followed by
extends MovieClip

means the events methods and properties of
the
Mov
ieClip
class are available to this new class


Lines 7 to 9 are the class constructor

the code invoked when an instance of the
class is created.





14

Inheritance


You can inherit useful methods and properties from a parent class in the child
classes you cre
ate as well as adding entirely new ones.




































------------------------------------------------------------------------------------------------------------


Notes taken from; Shupe, R.
(2008) Learning Actionscript 3
.0
a beginne
rs guide,
O’Reilly, Cambridge.



http://www.learningactionscript3.com/downloads/