web scripting for designers - CGR C/092 - fall 2003
Philip van Allen - v a n a l l e n @ a r t c e n t e r . e d u

room 133, Monday 4:00pm-7:00pm
room 133, Monday 7:00pm-10:00pm
all materials on this web site © copyright 2003, Philip van Allen
 
week 02 - flash scripting overview

 
introduction : 

  
Scripting in Flash - ActionScript overview

The scripting language in Flash is called ActionScript, which is modeled closely on the JavaScript language developed by Netscape and used in most web pages. Most concepts you learn for ActionScript will generally apply to other programming languages, and very closely match how JavaScript works.

This (and next) week's lesson provides a brief overview of general programming concepts, and some specifics of how coding in Flash works. In the coming weeks, we'll cover in detail each of the topics reviewed this week.

Try out each example as we go through the topics.

 


where code goes : 

ActionScript code can go in many different places inside a flash movie, and where it goes affects when the code is run.

  • Keyframes - ActionScript code can be attached to any keyframe, either in the main movie timeline, or in the timeline of a MovieClip. Scripts cannot be attached to a normal frame - they must be put on a keyframe.

    • Click on the keyframe to add a script to it.

      A script attached to a keyframe is run upon entry of the timeline into that frame. So if a script is on a keyframe on frame 15, the script will be run when the movie playhead crosses that frame. If the movie or MovieClip is stopped before frame 15, that script will not be run.

      Note that scripts in keyframes are run before any graphics are displayed for that frame. For example, if a script is on the first frame of the main movie, and that script changes the location of graphics on the screen, the user will only see the new locations of the graphics. I.e. the script is run and the graphics are moved before the first frame is displayed.
    • Example: Insert a keyframe at frame 15. Click on that keyframe, open the Actions window, set it to Expert Mode, and insert the following code:

      trace("got to frame 15");

  • Buttons and MovieClips - Scripts can be attached to instances of Buttons and MovieClips on the stage. Scripts cannot be attached to the symbols in the library, only to instances on the stage.
    • Click on the Button/MovieClip instance on the stage to add a script to it. You'll have to specify what event for that object will trigger the script--e.g. "on (release)" specifies that the script will be run when the mouse button is released.

      A script on a Button or MovieClip is run when some event occurs, regardless of the position of the timeline or if the timeline is playing or is stopped. An event can be a mouse click, the point at when the object first appears, or when some data is finished loading. When associated event occurs, the script is run.
    • Example: Create a movieclip and put it on the stage. Click on that movieclip, open the Actions window, set it to Expert Mode, and insert the following code:

      on (release) {
          trace("release event received");
      }

 

 
naming things : 

rules to live by

An important part of programming is moving and changing objects, which means that the objects must have names so the script can address them. You give names to variables, symbols, and instances of symbols. Because names are such a key aspect for programming, it is good policy to follow some standard naming conventions. In addition, some naming rules are enforced by ActionScript. The naming of variables is more restrictive than the naming of symbols, but it is wise to use the same rules for both.

Naming rules:

  • objects names must start with a letter or underscore "_"
  • letters and numbers are allowed, but no other characters except for "_"
  • don't use spaces in names
  • ActionScript does not pay attention to letter case, but JavaScript does, so be consistent in the user of letter case
  • in general, use a lowercase letter for the first character of a name
  • if there are multiple words in a name, use an "_" or upper case letter to indicate the start of a new work. e.g. firstVariable, first_variable.
  • name movieClip instances (the objects on the stage) with an "_mc" suffix. e.g. if the movie clip symbol is called ball, name the instance ball_mc

 

 
trace() output : 

your friend when experimenting and debugging

When developing scripts and learning about scripting in Flash, it is often useful to "see" what is going on inside the script. The easiest way to do this is by using something called the trace() function (another method uses the "debugger" which we'll cover later in the semester). The trace() function allows us to put messages in our scripts that are displayed in a special output window. This output window is visible only when testing the movie inside Flash.

Seeing what is going on inside your scripts is the only way to really understand scripting. Whether learning some new technique, or trying to fix a program that isn't doing what you want, the trace() function is an essential tool.

For example, do the following:

  • put a keyframe at frame 15 of the main movie
  • select the keyframe, and add the following script:

    trace("got to frame 15");
    count = count + 1;
    trace(count);

  • test the movie

You'll see when you run this movie that every time the movie hits frame 15, the message "got to frame 15" is displayed in the output window, along with the value of the variable count. Try the same test, but initialize the count variable in the first frame of the movie by adding the following code:

var count = 100;

To experiment a little more, add a keyframe at frame 2, give it a frame label of "main". Then add the following code to the end of the script on frame 15 (it causes the timeline to go to the frame labeled "main" after frame 15):

gotoAndPlay("main");

 

 
statements : 

tell the computer what to do

Statements are the basic building blocks of code—each statement does something. A program is composed of a list of statements that tell the computer what to do. They usually get executed one after the other, but some statements can alter the order of statement execution.

Statements are composed of elements such as:

  • variables
  • operators
  • functions
  • keywords
  • constants

There is a standard syntax for each type of statement, which we'll cover over the term. The basic rule of a statement is that it should end with a semicolon. Some examples of statements:

var x = 100;
var y = 15;
var total = x + y;
trace(total);

Sometimes, statements are grouped into blocks of code by putting the code between curly braces "{...}". For example, the conditional statement can use a statement block to run some code if the condition turns out to be true:

if (total > 100) {
   trace("total is more than 100");
   stop();
}


 
comments : 

tell yourself what's going on

Comments are used in script code to talk to the humans. In fact, the definition of a comment is that the computer completely ignores the comment. Comments are useful to describe what's going on in the code, both for yourself, and for others who may need to modify the code in the future.

The syntax for comments is to start it with two forward slashes "//". An alternate syntax is to put the comment between "/*" and "*/".

Here are some sample uses of comments:

// begin initialization section

var count = 100; // create the counter and set it's initial value
var name = "Phil"; // create the name variable, and set it's initial value to Phil

// end initialization section

 

/* This block of code demonstrates the use
   of trace(), incrementing a variable
   and sending the timeline to a specific
   frame label to start the loop over
*/
trace("got to frame 15"); // display the message
count = count + 1;        // increment the counter by 1
trace(count);             // display the new value of count
gotoAndPlay("main");      // go to the start of the loop

 

 
variables : 

the way to remember

Variables are used in programming to hold information for later use. For example, the current score in a game, or the location of a graphic on the screen. Variables are just containers that have a name, and hold some information which is called the value. In the above examples, "x", "y", and "total" are all variables. The value a variable contains can change over time if a statement causes the value to change, but the name of the variable always stays the same. For example we can change the value of the variable "total" with a simple assignment statement like:

total = 80;

In general, it is best to identify all the variables you will use in a Flash program by declaring the variables at the beginning. This is part of the initialization process included in most programs. For example, we can declare variables in the following statements:

var score; // creates the variable "score"
var score = 0; // creates and initializes
var x, y, total; // creates several variables at once

Variables can contain different kinds of values—the most common are:

  • integers (whole numbers)
  • floating point numbers (numbers with a fractional value after the decimal point)
  • strings (text)
  • booleans (true or false)

 

 
operators : 

how to get something done

Operators are symbols like "+" and ">" that are used to combine, change, or compare the things. They usually have something on either side, which are called the operands. The operands are what the operators use to produce a result. For example, the statement:

10 * 5;

takes the operands of 10 and 5, and multiplies them together, resulting in the value 50. But this statement doesn't do much, since the result isn't put anywhere. A more useful statement would be:

x = 10 * 5;

uses the "*" operator to multiply 10 and 5 first, and then uses the "=" operator to put the result of the first operation on the right, into the variable "x" on the left.

Some common operators are:

  • math: +, -, /, *
  • assignment:
    • "=" put the result of the expression on the right into the variable on the left
    • "+=" add the right expression to the left variable, and put it into the left
    • "-=" subtract right from left
    • "++" "--" add/subtract 1 from the left variable
  • comparison of numbers or strings: <, >, , >=, <=, ==, !=
  • string: + (concatenates text strings into one string)

An example of the string "+" operator, which concatenates several strings into one combined string:

var firstName = "Jane";
var lastName = "Doe";
var fullName = firstName + " " + lastName;
trace(fullName);

 

 
functions : 

the way to simplicity and clarity

When your software becomes more complex, it's possible to have hundreds of lines of code. Fortunately, there is a standard programming method to simplify your code called a function. Functions are a way to collapse a series of statements in a simple macro that can be run with a single command. This is useful if you find yourself needing to repeat the a set of operations in many different places in your software. Rather than writing the same series of statements over and over again, you can define them in a function once, and from then on run the function simply by calling it's name.

function functionName() {
    statement 1;
    statement 2;

    ...
}

Functions not only provide a way to collect a series of statements together, they also provide a way to make those statements operate on different input each time. This is accomplished with something called arguments, and makes the function more generalized. Instead of doing the exact same thing each time, the function can perform the same action on different data each time it is called. Instead of teaching the computer to walk from point A to point B, you teach the computer to walk from any point, to any other point. The function takes the arguements that are passed to it, processes them, and then returns the results to the code that "called" the function.

function functionName(argument1, argument2, ...) {
    statement 1;
    statement 2;

    ...
    return result;
}

For example, suppose you wanted to calculate the area of a rectangle over and over again. The following code would do this:

function area(theHeight, theWidth) { // declare function name/arguments
    return theHeight * theWidth;     // calculate the area, and return the result
}

area1 = area(10, 15);          // call the function with
                               // 10 for height, 15 for width
                               // the result is assigned to
                               // the variable "area1"
trace(area1);                  // display the result
area2 = area(23, 42);          // use the function w/new values
trace(area2);                  // display the new result

In addition to the functions you create, Flash includes many built-in functions. For example, trace() is a built-in function that takes an argument of the text to display, and shows it in the output window. gotoAndPlay() is another built-in function that takes a frame number or label as it's argument.

 

 
conditionals : 

make a decision and respond

The heart of programming is the ability to make the system respond in an appropriate way, depending on the varying conditions presented to the software. Those conditions may be different user selections, time passing, or even randomness. Conditional statements allow the program to determine if something is true or false (make a decision), and if it's true a block of code is run (respond). For example, you can use a conditional to test the time of day, and if it's evening, run some code that says "Good Evening" to the user.

The basic format of a conditional is:

if ( condition ) {
    statement 1;
    statement 2;
    ...

}

Note that the code between the curly braces will only be run if the condition is true. Here is an example of some code that tests if it is daytime:

var now = new Date();       // create date object w/current time
hours = now.getHours();     // get hours since midnight
if (hours < 19) {           // test to see if it's before 7pm
    trace("Good Day!");     // it is!
}
                            // execution of the program continues after the conditional
                            // regardless of the results of the test

In addition to the simple if statement, it is possible to run one set of code if the condition is true, and a different set of code if the condition is false. To do this, we add the "else" clause to the condition statement. The format for this is:

if ( condition ) {
    statements for true;
    ...

} else {
    statements for false;
    ...

}

For example, here is the daytime checking code that can now say if it is day or night.

var now = new Date();       // create date object w/current time
hours = now.getHours();     // get hours since midnight
if (hours < 19) {           // test to see if it's before 7pm
    trace("Good Day!");     // it is!
} else {
    trace("Good Evening!");
}

Of course, this code does not work quite right--what if it is 2am? If we modify the condition of the if statement to test the morning and evening, we can get a better result. For example: if (hours > 6 && hours < 19)

 

 
loops : 

do something over and over again

Programs are often required to repeat a sequence of statements a number of times. Sometimes, the requirement is to do something until some condition is true; for example move a graphic across the screen by 10 pixels until the graphic reaches the edge. Other times, the requirement is to simply repeat the statements a specific number of times; for example, draw 9 circles on the screen from top to bottom.

There are many different kinds of loops which will be covered later in the semester, but a simple one is the while loop. This is similar to the conditional, except that the block of code is executed repeatedly until the condition becomes false. The basic format is:

while ( condition ) {
    statements;
    ...

}

Here is an example of some code that does a multiplication table for the number 9:

var x = 1;                      // initialize the multiplier
while (x <= 10) {               // condition, if true, loop again
    y = 9 * x;                  // multiply 9 times the multiplier
    theText = "9 * " + x + " = " + y; // display text, e.g. "9 * 7 = 63"
    trace(theText);             // print the text
    x += 1;                     // increment the multiplier
}                               // go back to the start of the loop

 

 
the event model : 

react to the world

Developing interative software means setting up a system that responds to events in the world. In Flash, these events are typically mouse clicks or keystrokes. But interactive software can also respond to sound, heat, proximity, light and other input with the right kind of sensors in the evironment. These events are unprediticable, and the software has to be ready to respond whenever they occur. In modern computing systems, this is accomplished with an underlying system that is constantly waiting for an event. Once an event is noticed, the appropriate set of actions is executed for that event. The system continues to watch for events, running code each time an event occurs. This system is called an Event-Based Execution Model, and it determines how and when the code you write is run.

The simplest kind of event in Flash is the entering of a frame in the timeline. Any code that's in a frame is executed when the timeline hits that frame. Another kind of event is caused by clicking the mouse. You can set up Flash to respond to a mouse click by inserting a button on the stage, and then attaching event handler code to the button. This event handler specifies the kind of event to respond to, as well as the block of code to run if the event occurs.

For example, attach the following code to a button, and observe what happens:

on (press) {
    trace("Mouse Press");
}
on (release) {
    trace("Mouse Release");
}
on (rollOver) {
    trace("Mouse Over");
}
on (rollOut) {
    trace("Mouse Out");
}

 

 
objects : 

properties and methods for manipulation

ActionScript is an object oriented language, which is a fancy way to say that each element in Flash has its own characteristics and ways of manipulating it. One of the most important Flash objects are movieClips, which have a set of properties that include X-Y position, scale, and alpha settings. MovieClips also have methods that enable code to control the behavior of the clip. These include play(), stop(), startDrag(), and hitTest().

The properties and methods asssociated with each object enable the software to manipulate these objects simply by addressing the objects by name.

properties

For example, you can change a movieclip's position by changing its X and Y coordinates. Properties of objects are always addressed by using the dot syntax common to object oriented languages (including JavaScript). E.g. ball_mc._x is used to access the X position of the movieClip named ball_mc from the main timeline. As an alternative, a movieClip can refer to its own properties using the "this" keyword. E.g. this._y refers to the Y position of the current movieClip when the code is attached to that movieClip.

Do the following:

  • Create a new movieclip symbol with a circle, and call it "ball"
  • Place an instance of this movieclip on the stage, and name the instance "ballA_mc"

Put the following code on the movieClip:

onClipEvent(enterFrame) {
    this._x += 10;
    this._y += 10;
}

Each particular instance of the movie clip behaves independently from other instances the same movie clip. So if you put another instance of the ball clip on the stage, and named it ballB_mc, you could add the following code to the second movieClip, which would make the ball go in the opposite direction:

onClipEvent(enterFrame) {
    this._x -= 10; // could also be written _root.ballB_mc._x -= 10;
    this._y -= 10; // could also be written _root.ballB_mc._y -= 10;
}

By tradition, many of the properties begin with an underscore character "_". Other properties of movieClips include:

  • _alpha - transparency of the clip, 0-100
  • _xscale, yscale - horizontal (x) and vertical (y) scale of the clip in relation to its original symbol
  • _visible - visibility of the clip, true or false
  • _rotation - rotation of the clip in degrees, 0-360 (numbers can be > 360 or < 0)

A complete list of standard movieClip properties is on page 624 of the textbook (second edition).

methods

As mentioned, objects can also have various methods associated with the object that permit control over the object. These methods are essentially functions, and are addressed with the same dot syntax that is used for the property variables. So for example, if you place a movieClip on stage and add the following code to the clip, you will be able to drag it around.

on (press) {
    this.startDrag(); // when the user press the mouse,
                      // start dragging this clip
}
on (release) {
    this.stopDrag(); // when the user releases the mouse,
                     // stop dragging this clip
}

Note that instead of using the name of the clip, this example uses the keyword "this", which simply refers to movieClip in which the code resides.

Other methods of movieClips include:

  • play(), stop() - starts or stops the play of the movieclip timeline
  • gotoAndPlay(), gotoAndStop() - sends the timeline to a frame or frame label, and plays or stops
  • hitTest() - determines if clip intersects a point on the stage, or another clip
  • duplicateMovieClip() - makes a copy of the clip with a new name

A complete list of standard movieClip methods is on page 625 of the textbook.

 

 

all materials on this web site © copyright 2003, Philip van Allen

top