1 flash actionscript actionscript and objects control structures

45
1 Flash Actionscript Actionscript and Objects Control Structures

Post on 21-Dec-2015

283 views

Category:

Documents


3 download

TRANSCRIPT

1

Flash ActionscriptActionscript and ObjectsControl Structures

2

ActionScript and Objects

It should be apparent by now that ActionScript is to some extent an object oriented language.

When we have an instance of a symbol on the stage this is effectively an object. You can think of the symbol itself as being like a class (i.e. we can create new instances/objects from this class).

As with any object there are two types of things associated with it: 1. Properties 2. Methods

3

ActionScript and Objects

So when we create a circle symbol and then drag in onto the stage and call the instance ball we now have access to various properties of ball.

For example it has a number of frames, a position, and so on. We have already seen an example of directly altering its position.

• ball.x = mouseX;

4

ActionScript and Objects

There are also various commands and actions we can issue (i.e. ask the object to perform) e.g

• ball.stop();

These commands and actions are equivalent to methods.

5

The Math Object

Let’s look at another commonly used object, the Math object.

Go back to the text input example movie and change the ActionScript for the enter button to the following:

6

The Math Object

This shows the use of the sqrt method of the Math Object It’s also a good example of Type conversions

function updateOutput(event:MouseEvent):void

{

var pressedKey:String = entryText.text;

var calcValue:int = int(pressedKey);

var myCalculation = Math.sqrt(calcValue);

var finalOutput:String = String(myCalculation);

outputText.text = finalOutput;

}

entryButton.addEventListener(MouseEvent.CLICK,updateOutput); );

7

The Math Object

This does pretty much what you would expect it to …

If you have a look at the top level Actions window you will see all the other methods that the Math object offers

8

ActionScript Control Structures

Three basic control structures for programming languages: sequence selection iteration

These structures are necessary and sufficient to implement any algorithm.

9

ActionScript Control Structures

To make the job easier most programming languages provide higher-level structures for grouping and organising them: functions/methods objects

Syntax of the three basic control structures is the same for ActionScript as it is for many other programming languages such as C, Java etc…

10

Sequence

Sequence simply means the ability to execute a set of statements in order.

This is done by writing them in the order in which you wish them to be executed and separating them by semicolons e.g.

• S1;S2;S3;

Usually these are placed on separate lines e.g.• S1;• S2;• S3;

11

Sequence

For example:

ball.x = 20;

ball.y = 30;

ball.x = ball.x +1;

ball.y = ball.y +1;

12

Selection

Selection means the ability to choose between two (or more) different statements depending on the value of some condition.

It takes the general form

if (condition){

//statements;

}

It is worth looking briefly at how ActionScript handles conditions.

13

Selection

Conditions are formed by the use of a set of conditional operators. These are:

< less than> greater than<= less than or equal to>= greater than or equal to= = equal to!= not equal to

14

Selection

These operators can be used to compare the values of variables and/or literals. The result is that a Boolean value, true or false, is returned. E.g.:

x < 10 10 < 11

x >= y x = = y

15

Selection

These conditions could be used in selection (IF) statements as follows:

if (x < 10){ x++;} else{ x--; // and so on !}

Compound conditions can be formed by combining conditions using the logical operators. These are:

• ! Logical NOT• && Logical AND• || Logical OR

16

Selection

Logical NOT inverts the value of a condition. So if x<y is true then !(x<y) will be false.

A condition formed by the use of && will be true if and only if both of its constituent conditions are true.

A condition formed by the use of || will be true if one of its constituent conditions is true.

So suppose x has the value 5 and y has the value 0 then ….

(x<10) && (y>0) false (x<10) && (y>=0) true!(x<10) || (y<=0) ?

17

Selection

If statements can be formed without the else and they can also contain else if clauses also:

if (x<10){ x++;} else if (x<20){ x = x + 2;} else { x = 30;}

18

Selection

There are three general forms of the if selection structure. They are:

if (condition) { // statements; }

if (condition){ // statements;}else // statements;}

if (condition1){ // statements;}else if (condition2){ // statements;} . . .else{ // statements;}

19

Selection

Switch The switch statement is useful if you have several

execution paths that depend on the same condition expression.

It provides functionality similar to a long series of if…else if statements, but is somewhat easier to read.

Blocks of code begin with a case statement and end with a break statement.

For example, the following switch statement prints the day of the week, based on the day number returned by the Date.getDay() method:

20

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;

}

21

Selection

Let’s look at some examples of the use of selection statements.

Example 1: Space Invaders

I have a game of space invaders. The player’s ship is allowed to fire bullets at the aliens. Suppose the bullet has just been fired and this is signified by the Boolean variable bulletFired = true. Also the bullet is moving up the screen at a speed signified by the variable bulletSpeed. I want to move it further up the screen if it hasn’t already reached the top. If it’s at the top I want to stop moving the bullet and remove it from the screen. In this case I also want to set bulletFired to false , which Flash will see as a sign that the player is allowed to fire again.

22

Selection

Let’s draw a picture ...

23

Selection

Player’s ship is at the bottom and our bullet is at some point moving upwards.

In Flash the top-left hand corner of the screen is (0,0) so as we increase the x coordinate of an object it moves to the right and as we increase the y coordinate it moves down.

The bullet moves up in a straight line so only its y-coordinate decreases as it moves upwards eventually reaching a value of 0 at the top.

24

Selection

Suppose the instance of the ship on the screen is called ship, then its x coordinate is ship.x and its y coordinate is ship.y.

Similarly if the bullet is called bullet then its coordinates are bullet.x and bullet.y.

So bullet.y is positive as it is moving up the screen but if it is <=0 then it has moved off the top of the screen.

25

Selection

So as long as bullet.y is positive we want to keep subtracting from it which will move it upwards.

As soon as bullet.y is less than zero we no longer need to animate the bullet, although we need it to disappear.

Easiest way to do this is to place it off the screen, say by setting bullet.y = -100.

26

Selection

When the bullet is off the screen, the player would be allowed to fire another bullet, so we need to tell Flash this by making bulletFired = false. (This would have been set to true after the bullet was fired).

So the decision becomes If (the bullet is being fired) and (its y

position is greater than or equal to 0)• move the bullet

If (the bullet is being fired) and (its y position is less than or equal to 0)

• hide the bullet and let the user fire another.

27

Selection

This becomes …

if ((bulletFired=true) && (bullet.y>=0)){ bullet.y = bullet.y - speed; }else if (bulletFired=true && (bullet.y<0)){ bulletFired = false; bullet.y = -100; }

28

Selection

We need a bit more ActionScript to start thinking about coding this fully so instead lets look at a password screen.

Example 2: Password Field Suppose we want to password protect our Flash

website. We could do this by dividing it into two scenes. Scene

1 is a screen which puts up a text field and invites the user to enter a password.

If this password is correct then the movie jumps to scene 2. If not it doesn’t.

29

Selection

So this requires a simple if statement to implement (along with the textfields we have already seen).

We need two elements besides the static graphics. 1. A textfield. 2. A button (execute).

The idea is that when the user hits the execute button the system reads what is in the textfield and if it matches the password jumps to scene 2.

Assume we have already named the password textfield instance to be password and the button instance to be enterButton.

30

Selection

We need to attach the following action to frame one of our actions layer in scene 1.

stop();function checkPassword(event:MouseEvent):void {

if (password.text=="mypassword"){

gotoAndPlay(1,"Scene 2"); }} enterButton.addEventListener(MouseEvent.CLICK,checkPassword);

31

Selection

And the following to frame one of the actions layer in scene 2.

stop();

32

Selection

Example 3: Galaxians Imagine we are writing a piece of code which controls

how a diving space invader

attacks the player as it

advances down the screen. It should do different things

depending on how close it

gets to the player’s ship.

50

25

33

Selection

We might write the decision like this:

Remember it will only try the first else if branch if the if branch is false.

It will only try the second else if branch if the if and the first else if are false.

if (ship.y - alien.y > 50) { make alien stay in formation }else if (ship.y – alien.y > 25) { make alien start to fire on the ship and dive in a random manner }else if (ship.y – alien.y > 10) { execute kamikaze tactics }

34

Selection

What would happen if we changed the password code to the following?

stop();function checkPassword(event:MouseEvent):void {

if (password.text=="user1"){

gotoAndPlay(1,"Scene 2"); }

else if (password.text=="user2"){

gotoAndPlay(1,"Scene 3"); }} enterButton.addEventListener(MouseEvent.CLICK,checkPassword);

35

Looping

In any programming language you essentially have two different situations when employing a loop.

Either (a) you know how many times the loop has to be executed in advance or (b) you don’t.

36

Looping

An example of (a) would be adding up all the elements of an array. We know how many times we have to loop because we know how many elements there are in the array.

An example of (b) would be a situation where we want to keep repeating some action until the user presses a key indicating that we should stop.

We tend to use while loops for (b) and for loops for (a).

37

Looping

Let’s start with the while loop. Its general form is:

The condition is tested. If it is true then the statements are executed.

The condition is tested again. If true, the statements are executed.

This sequence continues until the condition is found to be false.

while (condition){ statement(s);}

38

Looping

In Flash these loops are used to obtain repetitive behaviour within a single frame.

This is different to the loops between frames which we have already seen by the use of the gotoAndPlay() action.

Let’s look at a substantial example of the use of while loops in Flash.

39

Looping

Example: Brownian Motion We are going to build a brownian motion simulator.

Gases are made up of lots of little particles that bounce around in a random motion. This is called brownian motion and is caused by the particles constantly hitting each other and shooting off in random directions after each collision. The effect we want to achieve is ...

40

Looping

1. Open a new movie and give it a black background. Create a graphic symbol called plasma that consists of a white circle with a radial gradient that fades to black at the edges. 2. Now create a new movie clip called randomplasma. This should be blank at present!. Drag the plasma graphic symbol onto the centre of the stage and use the Properties panel to centre it at 0.0, 0.0. Create a new layer called Actions.3. In frame 1 of the Actions layer (of the movie clip random plasma) add the following code in the Frame Actions window:

this.x = this.x + (Math.random()*4)-2;this.y = this.y + (Math.random()*4)-2;

4. Add a keyframe in frame 2 of the Actions layer and add a gotoAndPlay(1) action.5. Return to Scene 1 and drag three instances of the random plasma movie clip onto the stage. Test the movie (Plasma01.fla).

41

Looping

In this new layer we are going to clone our particle so we have lots of them in order to form a gas cloud.

We are going to use the new keyword to do this.

6. Delete two of the instances. Bring up the properties panel and give the movieclip an instance name, particle. 7. Go to the root timeline (e.g. Scene 1). Add a new layer called Actions.

42

Loading Symbols Dynamically

In order for this to work you must turn on the Export for ActionScript option in the Linkage properties for the target symbol.

Right click on the symbol in the Library and choose Linkage. Check ‘Export for Actionscript’.

Because you can no longer add an identifier, you have to handle everything instead using the class name. If you don't have a custom class for the symbol you want to attach, use the symbol name as inserted by default. In this case, Flash creates a skeleton class for you using the name of the symbol.

43

Loading Symbols Dynamically

This is the general form of the code:

var myInstance = new MyClassName(); addChild(myInstance);

44

Looping

8. In frame 1 of the new layer actions add the following code:

var counter:int = 10while (counter>0) {

var newParticle = new randomPlasma();addChild(newParticle);newParticle.x = particle.x;newParticle.y = particle.y;counter--;

}stop();

45

Looping

Something wrong with this … We were supposed to make the movie clip symbol

transparent to some degree ...

This works a bit better. Try it out with 100 instances instead ….

9. Edit the symbol plasma. Using the color mixer set it so the radial gradient goes from white/alpha 100% to white/alpha 0 %