35
Unit 7: Making Decisions and Repeating Yourself

ActionScript 9-10

  • Upload
    edison

  • View
    590

  • Download
    2

Embed Size (px)

DESCRIPTION

9 - 10

Citation preview

Page 1: ActionScript 9-10

Unit 7: Making Decisions and Repeating Yourself

Page 2: ActionScript 9-10

Topics

• Iteration (looping) statements• index loop: looping over arrays

• Conditional statements• if / else

• comparison operators: > >= < <= == != instanceof

• logical operators: || && !

Page 3: ActionScript 9-10

What is a “Loop" Statement?

• A loop ("iteration") statement re-executes specified code until a condition is met

• ActionScript supports four different loop statements• for

• for-in

• while

• do-while

Page 4: ActionScript 9-10

Using Index Loops and their Values

Page 5: ActionScript 9-10

for (“Index") Loop

• Counts from one number to another

• Most commonly used

Page 6: ActionScript 9-10

Bucle while

var aNames:Array = ["Fred", "Ginger", "Sam"];

while(aNames.length > 0)

{

trace("Names in array: " + aNames.length);

trace(aNames.pop());

}

El bucle while se ejecuta mientras su condición sea verdadera. Si nunca cambia nada en el código del bucle como para que la condición pase a ser falsa, se estará creando un bucle sin fin.

Page 7: ActionScript 9-10

Bucle do – while

var aNames:Array = [];

do

{

trace("Names in array: " + aNames.length);

trace(aNames.pop());

} while(aNames.length > 0)

El bucle do-while siempre se ejecuta por lo menos una vez. Después, continúa ejecutándose mientras su condición siga siendo verdadera.

En el código, vería “Names in array: 0”, aun cuando la condición es falsa,

porque la longitud de aNames no supera 0 y la condición no se ha comprobado hasta después

de que el código del bucle se ha ejecutado.

Page 8: ActionScript 9-10

• Attaching Multiple MovieClips from an Array of Data • Loop over the length of an array

• Trace index variables

• Use index variables to create unique instance names

• Use index variables to assign unique positions

• Assign array values for display in a dynamically generated MovieClip instance

Walkthrough 7-1

Page 9: ActionScript 9-10

Using Conditional Statements

Page 10: ActionScript 9-10

What's a “Conditional Statement"?

• A conditional statement tests whether one or more comparison expressions are true

• If the entire condition is true, specified code executes, else other tests or default code may execute

• ActionScript supports three types of conditional statements• if / else

• switch / case (not covered)

• Conditional operator (not covered)

Page 11: ActionScript 9-10

What's a “Comparison Expression"?

• ActionScript supports seven main comparison expressions

• Is it true that • x > y x is greater than y ?• x >= y x is greater than or equivalent to y ?

• x < y x is less than y ?• x <= y x is less than or equivalent to y ?

• x == y x is equivalent (not "equals") to y ?

• x != y x is not equivalent to y ?• x instanceof y x is an instance of a class named y

Page 12: ActionScript 9-10

How Does it Look in Code?

• If the expression is true, the code block executes

var password:String = "fly";

if (txtPassword.text == password) {

// runs if User typed "fly" in the password field

}

if (aPlayers instanceof Array) {

// runs if aPlayers is an instance of the Array class

}

Page 13: ActionScript 9-10

How Do I Ask if Something is False?

• ActionScript supports a "not" logical operator• Is it true that …

• !(this is true)

• is this expression not true (is it false)?

var password:String = "fly";

if (!(txtPassword.text == password)) {// runs if User typed anything but "fly" in

txtPassword

}

if (!(aPlayers instanceof Array)) {// runs if aPlayers is anything but an Array

}

Page 14: ActionScript 9-10

How Do I Ask More Than One Question at a Time?

• ActionScript supports "and" and "or" logical operators

• Is it true that • This is true && ("and") this is true

• Are both expressions true?

• This is true || ("or") this is true• Is either expression true?

Page 15: ActionScript 9-10

How Does It Look in Code?

• If the entire compound expression is true, the code will execute

if (expression1 && expression2) {// runs if expressions 1 and 2 are both true

}

if (expression3 || !(expression4)) {// runs if expression 3 is true or 4 is not true

}

Page 16: ActionScript 9-10

How Does It Look in Code?

• If the entire compound expression is true, the code will execute

if (txtPassword.text == "fly" && player.admin == true) {

adminMode(true);

}

if (player.highScore < 200 || !(player.status == "expert")) {

easyMode(true);

}

Page 17: ActionScript 9-10

Can I Ask Alternative Questions?

• An else if clause is tested only if the prior if is not true• Otherwise each if is separately tested

if (txtPassword.text == "fly") {

adminMode(true);

}

else if (player.highScore < 200) {

easyMode(true);

}

Page 18: ActionScript 9-10

Can I Have a Default?

• An else clause executes if none of the above are trueif (txtPassword.text == "fly") {

adminMode(true);

}

else if (player.highScore < 200) {

easyMode(true);

}

else

{

regularMode(true);

}

Page 19: ActionScript 9-10

Can I Nest My Conditions?

• Conditions may be nested, if a second condition only makes sense if a prior condition is true

if (this._rotation <= 0) {

this._xscale = this._xscale – 10;

if(this._xscale <= 0) {

this.unloadMovie();

}

}

Page 20: ActionScript 9-10

• Visually Toggling a MovieClip using Conditional Code • Test the value of visual properties

• Conditionally change MovieClip properties between states

Walkthrough 7-2

Page 21: ActionScript 9-10

• Responding to Random Rotation and Dynamically Generating Multiple MovieClips• Randomly calculate the change rate of a property

• Test to ensure a calculation is only made once

• Test for and respond to changes in property values

• Call a function a specified number of times

• Observing that each instance of MovieClip symbol is unique

Lab 7

Page 22: ActionScript 9-10

Unit 8: Animating with ActionScript

Page 23: ActionScript 9-10

Topics

• Implementing drag and drop functionality for a MovieClip

• Hit ("collision") testing between MovieClip instances

• Using an initialization object in the attachMovie method

• Using the onEnterFrame event handler

• Working with animation velocity and conditionally testing Stage bounds

Page 24: ActionScript 9-10

Dragging, Dropping, and Hit Testing MovieClip Objects

Page 25: ActionScript 9-10

startDrag() and stopDrag() are MovieClip methods

ball1.onPress = function():Void {

this.startDrag();

}

ball1.onRelease = function():Void {

this.stopDrag();

}

• startDrag(): attaches the instance to the mouse

• stopDrag(): releases the instance from the mouse

Different from startDrag(target) and stopDrag(target) global functions, so always precede with this

How Do I Let the User Pick up a MovieClip Instance and Move It?

Page 26: ActionScript 9-10

Every symbol instance has a bounding box

And, a symbol instance has some internal shape

What's the Difference Between a Bounding Box and Shape?

Page 27: ActionScript 9-10

hitTest() is a MovieClip method which returns true or false if its bounding box or shape is touching either a

target MovieClip object, or a specific x/y position• a target object or x/y position, with its bounding box

if(ball1.hitTest(ball2)) { … }

if(ball1.hitTest(250, 125)) { … }

• a target object or x/y position, with its internal shape• pass true as the optional shape flag argument

if(ball1.hitTest(ball2, true)) { … }

if(ball1.hitTest(250, 125, true)) { … }

How Do I Know if Two Objects are Touching?

Page 28: ActionScript 9-10

• Dragging, Dropping, and Hit Testing MovieClip Objects • Use onPress and onRelease event handler methods

• Use the startDrag and stopDrag methods

• Respond to collisions when dropping an object

Walkthrough 8-1

Page 29: ActionScript 9-10

Initializing MovieClip Objects with an onEnterFrame Event Handler

Page 30: ActionScript 9-10

Timeline animation occurs when the playhead enters a keyframe with different content than before

When Does Flash “Animation" Occur?

Page 31: ActionScript 9-10
Page 32: ActionScript 9-10

MovieClip instances broadcast the onEnterFrame event ("signal") each time the playhead enters a frame

• Change visual properties and you have animation

var velocity:Number = 10;

ball1.onEnterFrame = function():Void {

this._x += velocity;

}

• All onEnterFrame event handlers execute simultaneously, at the frame rate of the entire document

• There's no distinction between frames and keyframes in an onEnterFrame event handler

What's the onEnterFrame Event?

Page 33: ActionScript 9-10

Initialization objects are generic objects passed as an optional argument to the attachMovie() method

• All properties and methods of this object are inherited by (copied onto) the newly attached MovieClip object

var init:Object = new Object();

init._x = Math.round(Math.random() * 100);

init._y = Math.round(Math.random() * 100);

init.onPress = function():Void { this._alpha = 30 }

this.attachMovie("Box", "mcBox1", nextDepth, init);

// mcBox1 will have a randomized x/y position

// and will fade to 30 _alpha when pressed

How Do I “Initialize" an Attached MovieClip?

Page 34: ActionScript 9-10

Velocity or the change rate of an animated MovieClip may need to be calculated or change at run time

• Each dimension (x/y) may change at a different rate

init.xVelocity = Math.round(Math.random() * 10);

init.yVelocity = Math.round(Math.random() * 10);

init.onEnterFrame():Void {

this._x += this.xVelocity;

this._y += this.yVelocity;

}

• An object may need to reverse direction

if(this._x < 0 || this._x > 500) { this.yVelocity *= -1 }

Why Make “Velocity" a Variable?

Page 35: ActionScript 9-10

• Initializing Attached MovieClips with an onEnterFrame Handler • Use an initialization object when attaching MovieClip

objects

• Use the onEnterFrame event handler

• Randomly calculate velocity (change rate) for two dimensions

• Test for Stage boundaries during animation

• Hit test during animationWalkthrough 8-2