Week 3: Working with Display Objects, Arrays and Loops

>>>week3_examples

Topics:

  • Understanding Objects and Classes
  • Working with Display Objects
    • Understanding the Display List
    • Display Object Classes, Properties and Methods
    • Targeting Instances on the Timeline
    • Adding and Removing Objects Dynamically
      • Symbols from the Library
      • Text Fields
    • Arranging Objects
    • Targeting Objects
    • Adding Events to dynamically created objects
  •  Loops
  •  Arrays

ActionScript and OOP: Everything is an Object

Absolutely everything that you use in ActionScript is an Object, and each of those Objects is defined by a Class. When you installed the Flash IDE on your computer, you also installed the entire library of built-in classes that are the foundation of the ActionScript language. Objects represent a specific instance of a Class. Another way to look at it is that a Class is a blueprint for an Object. Classes in ActionScript are composed of three elements: Properties, Methods, and Events.

  • Properties are what Objects are
  • Methods are what Objects do
  • Events track when something happens that ActionScript can respond to

Methods and properties have a relationship to programming concepts that we have already explored. You can think of Properties as Variables that belong exclusively to a class, and Methods as Functions that do the same. Let’s look at the MovieClip class in the Help system to see how it is organized.

The Display List

In order for us to actually work with objects on the stage using Actionscript, we need to understand the Display List. Anything that appears on the stage is part of the Display List. The Display List is a hierarchy of the visual objects in your Flash movie. In other words, the display list of any Flash movie has a tree structure that is made up of nested Display Objects:

The Display List

The Stage is the base container, and every other object is nested inside of it.

Display Object Core ClassesDisplay Object Core Classes

The above diagram details all of the objects in the Display package. Today we are going to go over a portion of them.

Display Object

This is the base object, all other Display Objects inherit the properties and methods from this class. It contains generic properties such as x/y coordinates, width and height. All other Display Objects extend this class, either directly or indirectly.

Interactive Object

This class adds methods, properties and events that allow you to add user interactivity to a Display object.

Display Object Container

This class adds the ability of a Display Object to hold other Display Objects. The three classes above are abstract classes, which means that you can’t create instances of them, they are designed only to hold properties and methods that will be utilized by the child classes.

Sprite

This is a new type of Object in ActionScript 3.0, and there is no way to create a Sprite through the IDE, only via ActionScript. The Sprite is a stripped down version of the MovieClip, without any properties, methods, or events related to the timeline. Because of this reduced functionality, the Sprite is much lighter weight than the MovieClip.

MovieClip

The most important of the Display Objects, MovieClip adds frames, frame labels and scenes to the Sprite.

Targeting Instances on the Timeline

In order to manipulate a display object with AS, it must have a unique instancename. If the object is on the main timeline, it can be targeted directly:

myInstance.propertyname;

If the object is nested in another object’s timeline, you must access it via the parent object.

parentObject.myInstance.propertyname;

Manipulating Display Object Properties

You can manipulate the properties of any display object on the stage that has an instance name. These properties include:

  • x
  • y
  • width
  • height
  • scaleX
  • scaleY
  • rotation
  • alpha

Getting and Manipulating the Depth of Display Objects

Each display object is assigned a depth according to the order in which it was added to the stage, starting with zero and ascending. There are a number of methods for getting and setting object depths:

  • getChildIndex(objectname)
  • getChildAt(indexnumber)
  • setChildIndex(objectname, depth)
  • swapChildren(object1,object2)
  • swapChildrenAt(index1, index2)

Note: You can easily tell whether something is a property or a method of an object by the presence or lack of parentheses ( ) after the name. Methods have the parentheses so you can pass parameters to them, just like we passed parameters to our addMe function last week.

Adding Instances to the Display List from the library

When you are going to add an instance of a symbol from the library using ActionScript, you must make sure that you do a couple of new things when you create the symbol, or later using the properties panel.

  1. Name the symbol, make sure that the name is descriptive of what it is
  2. If it isn’t already open, click the Advanced button to reveal the advanced options
  3. Under linkage, click “Export for Actionscript” and “Export in Frame 1″
  4. For simplicity sake, Class should be the same name as the Name at the top
  5. Base class will default to MovieClip or Button, depending on what you selected above in the type field. If the symbol doesn’t need a timeline of its own, change this to flash.display.Sprite to save space in the timeline.

Step 1: Create the New Instance

Once your symbol is properly set up, you must first you must create the object instance using the new operator:

var myInstance:SymbolName = new SymbolName();

The instance name must be unique, and can not be the same as the symbol name.This instantiates the object, but it does not yet appear on the stage.

Step 2: Add the Instance to the Display List

You must add it as a child of the stage in order for it to become part of the Display List:

parentObject.addChild(myInstance);

You can also put a new child at a specific depth, although you can’t skip depths. If you put a child at a depth where one already exists, that one will be bumped up a level.

parentObject.addChildAt(myObject,depth);

The parent object can be any DisplayObjectContainer (MovieClip, Sprite, Stage, that is already in the Display List. Remember, this includes the stage!

Remove Objects from the Display List

This is a one step process:

parentObject.removeChild(myObject);

Or

parentObject.removeChildAt(myObject,depth);

If you want to add this object back again at a later point, you can do so just by using addChild, you don’t have to create the object again.

Using Arrays

An array is a data structure similar to a variable, in that it allows you to hold values in memory. The difference is that a variable can only hold one value at a time, where an array can hold multiple values. Another distinction is that an array can hold values of multiple datatypes. Arrays are used in applications where you need to track an ordered list of values.

There are several different ways to create and populate an array. The simplest way is to create an empty array of indeterminate length:

var myArray:Array = new Array( );

You’ll notice the new operator here for the first time. This allows you to create a new instance of almost any ActionScript object. We’ll get into it more later!

If you put a value in the parentheses after Array in this statement, you are passing a parameter to the array. If you pass a single number, this will determine the number of spaces in the array:

var myArray:Array = new Array(5);

This creates an array with 5 spaces.

If you put anything besides a single number into the parentheses, the value(s) will be the initial values stored in the array.

var myArray:Array = new Array("Apple","Banana","Pear","Peach");

However, we usually create and populate an array all in one go using an array literal, a comma separated list of values enclosed by square brackets:

var arrayName:Array = [ value1, value2, value3 ]

Each value in array is an element. The place that the element holds within the array is its index. In order to access a specific element within the array, you must refer to it by the index number. Important to note is that the first element in an array has an index of 0, not 1.

To access an element in an array, use the following syntax:
arrayName[index];

The index is the spot in the array you want to access.

Here’s an example that puts it all together:

//define the array
var fruit:Array = ["banana", "orange", "papaya", "pineapple"];
//access the value of an array element
trace (fruit[0]);

You can find out the length of any array like this:

trace (fruit.length);

If you want to redefine a value in an array, you do this:

fruit[1] = "Guava";

You can add a value to an array either of these ways:

fruit[4] = "Guava";

or

fruit.push("Guava");

The advantage to the second method is that you don’t need to know how many values are already in the array.

You can delete a value in the array with the delete keyword:

delete fruit[1];

This will leave a blank space in the array.

If you want to get rid of that spot in the array completely, you must use the splice method of the Array object:

fruit.splice(1,1);

This will remove 1 element starting at index 1 of the array.

If you want to sort the contents of an array,  you can use the sort method:

fruit.sort();

You can pass an options parameter to the sort method, here are just some of the options:

fruit.sort(Array.CASEINSENSITIVE);
fruit.sort(Array.DESCENDING);
fruit.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options

LiveDocs > Working with Arrays

LiveDocs > Array Reference

Using Loops

A loop is a block of code that is executed repeatedly based on a test expression. There are five types of loops: while, do-while, for, for-in, and for-each-in.

While Statement

A While statement executes while a test expression is true.
while (testExpression) {
codeBlock
}

You can see this looks very much like the if statement. The difference is that after the code block is executed the program returns to the beginning of the statement and evaluates the test expression again. If the test expression remains true, the code block is run again. This will continue until the test expression is evaluated as false.

If you create a while statement with a test expression that never evaluates as true, the loop will execute indefinitely, and Flash will generate a runtime error. Usually within the code block, you will include a statement that modifies the test expression. This will yield a false value for the test expression after the loop has executed the desired number of times:

var i:Number = 0;
while (i < 5) {
i = i + 1;
trace (i);
}

The variable name “i” is often used in a loop such as this. Like any variable, those used in a loop can have any name, but since this value is used as an incrementor, i is a recognizable shorthand for this use, and a common convention among programmers. There is also a new operator you can use in this case, the increment operator, which looks like this: ++. Placing this operator after a variable name will increase the value of the variable by one: i++. Our while loop example above can be simplified with the increment operator like so:

var i:Number = 0;
while (i < 5) {
i++;
trace (i);
}

There is also a decrement operator: –. When used after a variable name, it will decrease the variable value by one. So if you want your loop to count down to a value, instead of up, it could look like this:

var i:Number = 5;
while (i >= 0) {
i--;
trace (i);
}

do-while Statement

The do-while statement functions exactly the same as the while statement, except that the code block is placed before the test expression. This ensures that the code block will run at least once, even if the test expression evaluates as false the first time through. The syntax for the do-while statement is as follows:

do {
codeBlock
} while (testExpression);

For Statement

The for statement functions essentially the same as the while statement, but with a more compact syntax:

for (initialization; testExpression; update) {
codeBlock
}

The following example yields the same result as our original while statement, but in a much more compact way. Notice that the variable declaration and initialization, test case, and incrementor all take place within the test expression:

for (var i = 0; i <= 10; i++) {
trace(i);
}

Just like if statements, loops can be nested inside each other:

for (var i = 0; i <= 10; i++) {
trace("i="+i);
for (var j = 0; j <= 10; j++){
trace ("j="+j);
trace ("i*j="+j * i);
}
}

Using a loop with an array

Any type of loop statement is very useful for performing the same operation on all elements in an array. If we combine a for loop with the array we defined early, we can out all the values in the array sequentially:

for (var i = 0; i <= fruit.length; i++) {
trace(fruit[i]);}

Livedocs > Looping

Homework

1. Take the depth.fla example file, and add events to the symbols so that when you click any one it goes to the back.

2. Create a grid of images or animations dynamically added to the stage using loops. In addition to changing the x and y positions each time through the loop, you must also change the values of a least two other properties. Add an event to each instance so that when you click it, something happens. This is what I mean by a grid:

3. Taking my madlib.fla example as the starting point, create your own MadLib allowing the user to input at least 15 words. Use an array to store the words.

Textbook

Someone asked last week what was a good text for what we are learning in class. This one doesn’t exactly follow what we are doing, but it’s a good reference:

Foundation ActionScript 3.0 for Flash and Flex

2 thoughts on “Week 3: Working with Display Objects, Arrays and Loops

  1. There is also problem with the madlib file. Thanks.
    “[object InputScreen]
    [object InputScreen]
    TypeError: Error #1010: A term is undefined and has no properties.
    at madlib_CS4_fla::MainTimeline/onGoClick()

Leave a Reply