What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Create Interaction with ActionScript in Flash

Creating Interaction with ActionScript

About events and interaction

Controlling SWF file playback

Jumping to a frame or scene

Playing and stopping movie clips

Jumping to a different URL

Creating a custom mouse pointer

Getting the pointer position

Capturing keypresses

Setting color values

Creating sound controls

Detecting collisions

Creating a simple line drawing tool

Creating runtime data bindings using ActionScript

Creating bindings between UI components using ActionScript

Using components, bindings, and custom formatters

Adding and binding components on the Stage

Deconstructing a sample script

Creating Interaction with ActionScript

TOP

In simple animations, Macromedia Flash Player plays the scenes and frames of a SWF file sequentially. In an interactive SWF file, your audience uses the keyboard and mouse to jump to different parts of a SWF file, move objects, enter information in forms, and perform many other interactive operations.

You use ActionScript to create scripts that tell Flash Player what action to perform when an event occurs. Some events that can trigger a script occur when the playhead reaches a frame, when a movie clip loads or unloads, or when the user clicks a button or presses a key.

A script can consist of a single command, such as instructing a SWF file to stop playing, or a series of commands and statements, such as first evaluating a condition and then performing an action. Many ActionScript commands are simple and let you create basic controls for a SWF file. Other actions require some familiarity with programming languages and are intended for advanced development.

About events and interaction

Controlling SWF file playback

Creating interactivity and visual effects

Creating runtime data bindings using ActionScript

Deconstructing a sample script

About events and interaction

TOP

Whenever a user clicks the mouse or presses a key, that action generates an event. These types of events are generally called user events because they are generated in response to some action by the user. You can write ActionScript to respond to, or handle, these events. For example, when a user clicks a button, you might want to send the playhead to another frame in the SWF file or load a new web page into the browser.

In a SWF file, buttons, movie clips, and text fields all generate events to which you can respond. ActionScript provides three ways to handle events: event handler methods, event listeners, and on() and onClipEvent() handlers. For more information about events and handling events, see Handling Events.
 

Controlling SWF file playback

TOP

The following ActionScript functions let you control the playhead in the timeline and load a new web page into a browser window:

  • The gotoAndPlay() and gotoAndStop() functions send the playhead to a frame or scene. These are global functions that you can call from any script. You can also use theMovieClip.gotoAndPlay() and MovieClip.gotoAndStop() methods to navigate the timeline of a specific movie clip object. See Jumping to a frame or scene.

  • The play() and stop() actions play and stop SWF files. See Playing and stopping movie clips.

  • The getURL() action jumps to a different URL. See Jumping to a different URL.

Jumping to a frame or scene

TOP

To jump to a specific frame or scene in the SWF file, you can use the gotoAndPlay() and gotoAndStop() global functions or the equivalent MovieClip.gotoAndPlay() and MovieClip.gotoAndStop() methods of the MovieClip class. Each function or method lets you specify a frame to jump to in the current scene. If your document contains multiple scenes, you can specify a scene and frame where you want to jump.

The following example uses the global gotoAndPlay() function within a button object's onRelease event handler to send the playhead of the timeline that contains the button to Frame 10:

jump_btn.onRelease = function () {

gotoAndPlay(10);

};

In the next example, the MovieClip.gotoAndStop() method sends the timeline of a movie clip instance named categories_mc to Frame 10 and stops. When you use the MovieClip methods gotoAndPlay() and gotoAndStop(), you must specify an instance to which the method applies.

jump_btn.onPress = function () {

categories_mc.gotoAndStop(10);

};

In the final example, the global gotoAndStop() function is used to move the playhead to Frame 1 of Scene 2. If no scene is specified, the playhead goes to the specified frame in the current scene. You can use the scene parameter only on the root timeline, not within timelines for movie clips or other objects in the document.

nextScene_mc.onRelease = function() {

gotoAndStop("Scene 2", 1);

}
 

Playing and stopping movie clips

TOP

Unless it is instructed otherwise, after a SWF file starts, it plays through every frame in the timeline. You can start or stop a SWF file by using the play() and stop() global functions or the equivalent MovieClip methods. For example, you can use stop() to stop a SWF file at the end of a scene before proceeding to the next scene. After a SWF file stops, it must be explicitly started again by calling play() or gotoAndPlay().

You can use the play() and stop() functions or MovieClip methods to control the main timeline or the timeline of any movie clip or loaded SWF file. The movie clip you want to control must have an instance name and must be present in the timeline.

The following on(press) handler attached to a button starts the playhead moving in the SWF file or movie clip that contains the button object:

// Attached to a button instance

on (press) {

// Plays the timeline that contains the button

play();

}

This same on() event handler code produces a different result when attached to a movie clip object rather than a button. When attached to a button object, statements made within an on() handler are applied to the timeline that contains the button, by default. However, when attached to a movie clip object, statements made within an on() handler are applied to the movie clip to which the on() handler is attached.

For example, the following onPress() handler code stops the timeline of the movie clip to which the handler is attached, not the timeline that contains the movie clip:

// Attached to the myMovie_mc movie clip instance

myMovie_mc.onPress() {

stop();

};

The same conditions apply to onClipEvent() handlers attached to movie clip objects. For example, the following code stops the timeline of the movie clip that bears the onClipEvent() handler when the clip first loads or appears on the Stage:

onClipEvent(load) {

stop();

}
 

Jumping to a different URL 

TOP

To open a web page in a browser window, or to pass data to another application at a defined URL, you can use the getURL() global function or the MovieClip.getURL() method. For example, you can have a button that links to a new website, or you can send timeline variables to a CGI script for processing in the same way as you would an HTML form. You can also specify a target window, the same as you would when targeting a window with an HTML anchor tag (<a></a>).

For example, the following code opens the macromedia.com home page in a blank browser window when the user clicks the button instance named homepage_btn:

// Attach to frame

homepage_btn.onRelease = function () {

getURL("http://www.macromedia.com", "_blank");

};

You can also send variables along with the URL, using GET or POST methods. This is useful if the page you are loading from an application server, such as a ColdFusion server (CFM) page, expects to receive form variables. For example, suppose you want to load a CFM page named addUser.cfm that expects two form variables, firstName and age. To do this, you can create a movie clip named variables_mc that defines those two variables, as shown in the following example:

variables_mc.firstName = "Francois";

variables_mc.age = 32;

The following code then loads addUser.cfm into a blank browser window and passes variables_mc.name and variables_mc.age in the POST header to the CFM page:
variables_mc.getURL("addUser.cfm", "_blank", "POST");

The functionality of getURL() is dependent on what browser you use. The most reliable way to get all browsers to work the same is to call a JavaScript function in the HTML code that uses the JavaScript window.open() method to open a window. Add the following HTML and JavaScript within your HTML template:

<script language="JavaScript">

<--

function openNewWindow(myURL) {

window.open(myURL, "targetWindow");

}

// -->

</script>

You can use the following ActionScript to call openNewWindow from your SWF file:

var myURL:String = "http://foo.com";

getURL("javascript:openNewWindow('" + String(myURL) + "');");

 

Creating a custom mouse pointer

TOP

A standard mouse pointer is the operating system's on-screen representation of the position of the user's mouse. By replacing the standard pointer with one you design in Flash, you can integrate the user's mouse movement within the SWF file more closely. The sample in this section uses a custom pointer that looks like a large arrow. The power of this feature, however, is your ability to make the custom pointer look like anything--for example, a football to be carried to the goal line or a swatch of fabric pulled over a chair to change its color.

To create a custom pointer, you design the pointer movie clip on the Stage. Then, in ActionScript, you hide the standard pointer and track its movement. To hide the standard pointer, you use the hide() method of the built-in Mouse class (see hide (Mouse.hide method) in the ActionScript 2.0 Language Reference). To see an animated demonstration of a custom pointer, move your pointer over the following SWF file.

To create a custom pointer:

  1. Create a movie clip to use as a custom pointer, and place an instance of the clip on the Stage.

  2. Select the movie clip instance on the Stage.

  3. In the Property inspector, type cursor_mc in the Instance Name text box.

  4. Select Frame 1 of the Timeline, and type the following code in the Actions panel:

    Mouse.hide();

    cursor_mc.onMouseMove = function() {

    this._x = _xmouse;

    this._y = _ymouse;

    updateAfterEvent();

    };

    The Mouse.hide() method hides the pointer when the movie clip first appears on the Stage; the onMouseMove function positions the custom pointer at the same place as the pointer and calls updateAfterEvent() whenever the user moves the mouse.

    The updateAfterEvent() function immediately refreshes the screen after the specified event occurs, rather than when the next frame is drawn, which is the default behavior.in the ActionScript 2.0 Language Reference.)

  5. Select Control > Test Movie to test your custom pointer.

Buttons still function when you use a custom mouse pointer. It's a good idea to put the custom pointer on the top layer of the timeline so that, as you move the mouse in the SWF file, the custom pointer appears in front of buttons and other objects in other layers. Also, the tip of a custom pointer is the registration point of the movie clip you're using as the custom pointer.

Therefore, if you want a certain part of the movie clip to act as the tip of the pointer, set the registration point coordinates of the clip to be that point.

 

Getting the pointer position

TOP

You can use the _xmouse and _ymouse properties to find the location of the pointer in a SWF file. These properties could be used, for example, in a map application that gets the values of the _xmouse and _ymouse properties and uses the values to calculate the longitude and latitude of a specific location.

Each timeline has an _xmouse and _ymouse property that returns the location of the pointer within its coordinate system. The position is always relative to the registration point. For the main timeline (_level0), the registration point is the upper left corner. For a movie clip, the registration point depends on the registration point set when the clip was created or its placement on the Stage.

To see the _xmouse and _ymouse properties within the main timeline and a movie clip timeline, run the following SWF file and move your pointer. The updated coordinates on the right reflect the pointer position relative to the registration point of the smaller movie clip. The coordinates on the left reflect the pointer position on the larger SWF file.

The following procedure shows several ways to get the pointer position within the main timeline or within a movie clip.

To get the current pointer position:

  1. Create two dynamic text fields, and name them box1_txt and box2_txt.

  2. Add labels for the text boxes: x position and y position, respectively.

  3. Select Window > Actions to open the Actions panel if it is not already open.

  4. Add the following code to the script pane:

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function() {

    // returns the X and Y position of the mouse

    box1_txt.text = _xmouse;

    box2_txt.text = _ymouse;

    };

    Mouse.addListener(mouseListener);

  5. Select Control > Test Movie to test the Flash movie. The box1_txt and box2_txt fields show the position of the pointer while you move it over the Stage.
     

Capturing keypresses 

TOP


You can use the global on() handler to intercept the built-in behavior of keypresses in Flash Player, as shown in the following example:

/* When you press the Left or Right Arrow key, the movie clip to which the handler is attached changes transparency. */

on (keyPress "<Left>") {

this._alpha -= 10;

}

on (keyPress "<Right>") {

this._alpha += 10;

}

Make sure that you select Control > Disable Keyboard Shortcuts, or certain keys with built-in behavior won't be overridden when you use Control > Test Movie to test the application. See the keyPress parameter of on handler in the ActionScript 2.0 Language Reference.

You can use the methods of the built-in Key class to detect the last key that the user pressed. The Key class does not require a constructor function; to use its methods, you call the methods on the class, as shown in the following example:

Key.getCode();

You can obtain either virtual key codes or American Standard Code for Information Interchange (ASCII) values of keypresses:

  • To obtain the virtual key code of the last key pressed, use the getCode() method.
  • To obtain the ASCII value of the last key pressed, use the getAscii() method.

A virtual key code is assigned to every physical key on a keyboard. For example, the left arrow key has the virtual key code 37. By using a virtual key code, you ensure that your SWF file's controls are the same on every keyboard, regardless of language or platform.

ASCII values are assigned to the first 127 characters in every character set. ASCII values provide information about a character on the screen. For example, the letter "A" and the letter "a" have different ASCII values.

To decide which keys to use and determine their virtual key codes, use one of the following approaches:

  • See the list of key codes in Keyboard Keys and Key Code Values.
  • Use a Key class constant. (In the Actions toolbox, click ActionScript 2.0 Classes > Movie > Key > Constants.)
  • Assign the following onClipEvent() handler to a movie clip, and select Control > Test Movie and press the desired key:

onClipEvent(keyDown) {

trace(Key.getCode());

}

The key code of the desired key appears in the Output panel.

A common place to use Key class methods is within an event handler. In the following SWF file, the user can move the car using the arrow keys. The Key.isDown() method indicates whether the key being pressed is the right, left, up, or down arrow. The event listener, Key.onKeyDown, determines the Key.isDown(keyCode) value from the if statements. Depending on the value, the handler instructs Flash Player to update the position of the car and to show the direction.

The following example shows how to capture keypresses to move a movie clip up, down, left, or right on the Stage, depending on which corresponding arrow key (up, down, left, or right) is pressed. Also, a text field shows the name of the pressed key.

To create a keyboard-activated movie clip:

  1. On the Stage, create a movie clip that can move in response to keyboard arrow activity.

    In this example, the movie clip instance name is car_mc.

  2. Select Frame 1 in the Timeline; then select Window > Actions to open the Actions panel if it is not already visible.
  3. To set how far the car moves across the screen with each keypress, define a distance variable and set its value to 10:

    var distance:Number = 10;

  4. Add the following ActionScript code to the Actions panel below the existing code:

    this.createTextField("display_txt", 999, 0, 0, 100, 20);

  5. To create the event handler for the car movie clip that checks which arrow key (left, right, up, or down) is currently pressed, add the following code to the Actions panel:

    var keyListener:Object = new Object();

    keyListener.onKeyDown = function() {

    };

    Key.addListener(keyListener);

  6. To check if the Left Arrow key is pressed and to move the car movie clip accordingly, add code to the body of the onEnterFrame event handler.

    Your code should look like the following example (new code is in boldface):

    var distance:Number = 10;

    this.createTextField("display_txt", 999, 0, 0, 100, 20);

    var keyListener:Object = new Object();

    keyListener.onKeyDown = function() {

    if (Key.isDown(Key.LEFT)) {

    car_mc._x = Math.max(car_mc._x - distance, 0);

    display_txt.text = "Left";

    }

    };

    Key.addListener(keyListener);

    If the Left Arrow key is pressed, the car's _x property is set to the current _x value minus distance or the value 0, whichever is greater. Therefore, the value of the _x property can never be less than 0. Also, the word Left should appear in the SWF file.

  7. Use similar code to check if the Right, Up, or Down Arrow key is being pressed.

    Your complete code should look like the following example (new code is in boldface):

    var distance:Number = 10;

    this.createTextField("display_txt", 999, 0, 0, 100, 20);

    var keyListener:Object = new Object();

    keyListener.onKeyDown = function() {

    if (Key.isDown(Key.LEFT)) {

    car_mc._x = Math.max(car_mc._x - distance, 0);

    display_txt.text = "Left";

    } else if (Key.isDown(Key.RIGHT)) {

    car_mc._x = Math.min(car_mc._x + distance, Stage.width - car_mc._width);

    display_txt.text = "Right";

    } else if (Key.isDown(Key.UP)) {

    car_mc._y = Math.max(car_mc._y - distance, 0);

    display_txt.text = "Up";

    } else if (Key.isDown(Key.DOWN)) {

    car_mc._y = Math.min(car_mc._y + distance, Stage.height - car_mc._height);

    display_txt.text = "Down";

    }

    };

    Key.addListener(keyListener);]

  8. Select Control > Test Movie to test the file.
     
Setting color values

TOP

You can use the methods of the built-in ColorTransform class (flash.geom.ColorTransform) to adjust the color of a movie clip. The rgb property of the ColorTransform class assigns hexadecimal red, green, blue (RGB) values to the movie clip. The following example uses rgb to change an object's color, based on which button the user clicks.

To set the color value of a movie clip:

  1. Create a new Flash document and save it as setrgb.fla.

  2. Select the Rectangle Tool and draw a large square on the Stage.

  3. Convert the shape to a movie clip symbol and give the symbol an instance name of car_mc in the Property inspector.

  4. Create a button symbol named colorChip, place four instances of the button on the Stage, and name them red_btn, green_btn, blue_btn, and black_btn.

  5. Select Frame 1 in the main Timeline, and select Window > Actions.

  6. Add the following code to Frame 1 of the main Timeline:

    import flash.geom.ColorTransform;

    import flash.geom.Transform;

    var colorTrans:ColorTransform = new ColorTransform();

    var trans:Transform = new Transform(car_mc);

    trans.colorTransform = colorTrans;

  7. To make the blue button change the color of the car_mc movie clip to blue, add the following code to the Actions panel:

    blue_btn.onRelease = function() {

    colorTrans.rgb = 0x333399; // blue

    trans.colorTransform = colorTrans;

    };

    The preceding snippet of code changes the rgb property of the color transform object and reapplies the color tranform effect to the car_mc movie clip whenever the button is pressed.

  8. Repeat step 7 for the other buttons (red_btn, green_btn, and black_btn) to change the color of the movie clip to the corresponding color.

    Your code should now look like the following example (new code is in bold):

    import flash.geom.ColorTransform;

    import flash.geom.Transform;

    var colorTrans:ColorTransform = new ColorTransform();

    var trans:Transform = new Transform(car_mc);

    trans.colorTransform = colorTrans;

    blue_btn.onRelease = function() {

    colorTrans.rgb = 0x333399; // blue

    trans.colorTransform = colorTrans;

    };

    red_btn.onRelease = function() {

    colorTrans.rgb = 0xFF0000; // red

    trans.colorTransform = colorTrans;

    };

    green_btn.onRelease = function() {

    colorTrans.rgb = 0x006600; // green

    trans.colorTransform = colorTrans;

    };

    black_btn.onRelease = function() {

    colorTrans.rgb = 0x000000; // black

    trans.colorTransform = colorTrans;

    };

  9. Select Control > Test Movie to change the color of the movie clip.
     

Creating sound controls

TOP

You use the built-in Sound class to control sounds in a SWF file. To use the methods of the Sound class, you must first create a Sound object. Then you can use the attachSound() method to insert a sound from the library into a SWF file while the SWF file is running.

To see an animated demonstration of sound controls, click Play and adjust the volume and pan.

The Sound class's setVolume() method controls the volume, and the setPan() method adjusts the left and right balance of a sound.

The following procedures show how to create sound controls.

To attach a sound to a timeline:

  1. Select File > Import to import a sound.

  2. Select the sound in the library, right-click (Windows) or Control-click (Macintosh), and select Linkage.

  3. Select Export for ActionScript and Export in First Frame; then give the sound the identifier a_thousand_ways.

  4. Add a button to the Stage and name it play_btn.

  5. Add a button to the Stage and name it stop_btn.

  6. Select Frame 1 in the main Timeline, and select Window > Actions.

    Add the following code to the Actions panel:

    var song_sound:Sound = new Sound();

    song_sound.attachSound("a_thousand_ways");

    play_btn.onRelease = function() {

    song_sound.start();

    };

    stop_btn.onRelease = function() {

    song_sound.stop();

    };

    This code first stops the speaker movie clip. It then creates a new Sound object (song_sound) and attaches the sound whose linkage identifier is a_thousand_ways. The onRelease event handlers associated with the playButton and stopButton objects start and stop the sound by using the Sound.start() and Sound.stop() methods, and also play and stop the attached sound.

  7. Select Control > Test Movie to hear the sound.

To create a sliding volume control:

  1. Using the Rectangle Tool, draw a small rectangle on the Stage, approximately 30 pixels high by 10 pixels wide.

  2. Select the Selection Tool and double-click the shape on the Stage.

  3. Press F8 to open the Convert to Symbol dialog box.

  4. Select the Button type, enter a symbol name of volume, and click OK.

  5. With the button symbol selected on the Stage, enter the instance name of handle_btn in the Property inspector.

  6. Select the button, and select Modify > Convert to Symbol.

    Be careful to select the movie clip behavior. This creates a movie clip with the button on Frame 1.

  7. Select the movie clip, and enter volume_mc as the instance name in the Property inspector.

  8. Select Frame 1 of the main Timeline, and select Window > Actions.

  9. Enter the following code into the Actions panel:

    this.createTextField("volume_txt", 10, 30, 30, 200, 20);

    volume_mc.top = volume_mc._y;

    volume_mc.bottom = volume_mc._y;

    volume_mc.left = volume_mc._x;

    volume_mc.right = volume_mc._x + 100;

    volume_mc._x += 100;

    volume_mc.handle_btn.onPress = function() {

    startDrag(this._parent, false, this._parent.left, this._parent.top, this._parent.right, this._parent.bottom);

    };

    volume_mc.handle_btn.onRelease = function() {

    stopDrag();

    var level:Number = Math.ceil(this._parent._x - this._parent.left);

    this._parent._parent.song_sound.setVolume(level);

    this._parent._parent.volume_txt.text = level;

    };

    volume_mc.handle_btn.onReleaseOutside = slider_mc.handle_btn.onRelease;

    The startDrag() parameters left, top, right, and bottom are variables set in a movie clip action.

  10. Select Control > Test Movie to use the volume slider.

To create a sliding balance control:

  1. Use the Rectangle Tool to draw a small rectangle on the Stage, approximately 30 pixels high by 10 pixels wide.

  2. Select the Selection Tool and double-click the shape on the Stage.

  3. Press F8 to launch the Convert to Symbol dialog box.

  4. Select the Button type, enter a symbol name of balance, and click OK.

  5. With the button symbol selected on the Stage, enter an instance name of handle_btn in the Property inspector.

  6. Select the button, and select Modify > Convert to Symbol.

    Be careful to select the movie clip behavior. This creates a movie clip with the button on Frame 1.

  7. Select the movie clip, and enter balance_mc as the instance name in the Property inspector.]

  8. Enter the following code into the Actions panel:

    balance_mc.top = balance_mc._y;

    balance_mc.bottom = balance_mc._y;

    balance_mc.left = balance_mc._x;

    balance_mc.right = balance_mc._x + 100;

    balance_mc._x += 50;

    balance_mc.handle_btn.onPress = function() {

    startDrag(this._parent, false, this._parent.left, this._parent.top, this._parent.right, this._parent.bottom);

    };

    balance_mc.handle_btn.onRelease = function() {

    stopDrag();

    var level:Number = Math.ceil((this._parent._x - this._parent.left - 50) * 2);

    this._parent._parent.song_sound.setPan(level);

    };

    balance_mc.handle_btn.onReleaseOutside = balance_mc.handle_btn.onRelease;

    The startDrag() parameters left, top, right, and bottom are variables set in a movie clip action.

  9. Select Control > Test Movie to use the balance slider.
     

Detecting collisions

TOP

The hitTest() method of the MovieClip class detects collisions in a SWF file. It checks to see if an object has collided with a movie clip and returns a Boolean value (true or false).

You would want to know whether a collision has occurred either to test if the user has arrived at a certain static area on the Stage, or to determine when one movie clip has reached another.

With hitTest(), you can determine these results.

You can use the parameters of hitTest() to specify the x and y coordinates of a hit area on the Stage or use the target path of another movie clip as a hit area. When you specify x and y, hitTest() returns true if the point identified by (x, y) is a non-transparent point. When a target is passed to hitTest(), the bounding boxes of the two movie clips are compared. If they intersect, hitTest() returns true. If the two boxes do not intersect, hitTest() returns false.

Move the pointer over the shape in the SWF file to test the collision. The results of the hitTest() method are returned in the text field.

You can also use hitTest() to test a collision between two movie clips.

To test the collision, drag the car movie clip so that it touches the parking area movie clip. The results of the hitTest() method are returned in the text field.

The following example shows how to detect a collision between a mouse and movie clips on the Stage.

To detect a collision between a movie clip and the mouse pointer:

  1. Select the first frame on Layer 1 in the Timeline.

  2. Select Window > Actions to open the Actions panel, if it is not already open.

  3. Add the following code in the Actions panel:

    this.createEmptyMovieClip("box_mc", 10);

    with (box_mc) {

    beginFill(0xFF0000, 100);

    moveTo(100, 100);

    lineTo(200, 100);

    lineTo(200, 200);

    lineTo(100, 200);

    lineTo(100, 100);

    endFill();

    }

    this.createTextField("status_txt", 999, 0, 0, 100, 22);

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    status_txt.text = _level0.hitTest(_xmouse, _ymouse, true);

    }

    Mouse.addListener(mouseListener);

  4. Select Control > Test Movie, and move the pointer over the movie clip to test the collision.

The value true appears whenever the pointer is over a non-transparent pixel.

To perform collision detection on two movie clips:

  1. Drag two movie clips to the Stage, and give them the instance names car_mc and area_mc.

  2. Select Frame 1 on the Timeline.

  3. Select Window > Actions to open the Actions panel, if it is not already visible.

  4. Enter the following code in the Actions panel:

    this.createTextField("status_txt", 999, 10, 10, 100, 22);

    area_mc.onEnterFrame = function() {

    status_txt.text = this.hitTest(car_mc);

    };

    car_mc.onPress = function() {

    this.startDrag(false);

    updateAfterEvent();

    };

    car_mc.onRelease = function() {

    this.stopDrag();

    };

  5. Select Control > Test Movie, and drag the movie clip to test the collision detection.

Whenever the bounding box of the car intersects the bounding box of the area, the status is true.
 

Creating a simple line drawing tool

TOP

You can use methods of the MovieClip class to draw lines and fills on the Stage as the SWF file plays. This lets you create drawing tools for users and draw shapes in the SWF file in response to events. The drawing methods are beginFill(), beginGradientFill(), clear(), curveTo(), endFill(), lineTo(), lineStyle(), and moveTo().

You can apply these methods to any movie clip instance (for example, myClip.lineTo()), or to a level (_level0.curveTo()).

The lineTo() and curveTo() methods let you draw lines and curves, respectively. You specify a line color, thickness, and alpha setting for a line or curve with the lineStyle() method. The moveTo() drawing method sets the current drawing position to the x and y Stage coordinates that you specify.

The beginFill() and beginGradientFill() methods fill a closed path with a solid or gradient fill, respectively, and endFill() applies the fill specified in the last call to beginFill() or beginGradientFill(). The clear() method erases what's been drawn in the specified movie clip object.

To create a simple line drawing tool:

  1. In a new document, create a button on the Stage, and enter clear_btn as the instance name in the Property inspector.

  2. Select Frame 1 in the Timeline.

  3. Select Window > Actions to open the Actions panel, if it is not already visible.

  4. In the Actions panel, enter the following code:

    this.createEmptyMovieClip("canvas_mc", 999);

    var isDrawing:Boolean = false;

    //

    clear_btn.onRelease = function() {

    canvas_mc.clear();

    };

    //

    var mouseListener:Object = new Object();

    mouseListener.onMouseDown = function() {

    canvas_mc.lineStyle(5, 0xFF0000, 100);

    canvas_mc.moveTo(_xmouse, _ymouse);

    isDrawing = true;

    };

    mouseListener.onMouseMove = function() {

    if (isDrawing) {

    canvas_mc.lineTo(_xmouse, _ymouse);

    updateAfterEvent();

    }

    };

    mouseListener.onMouseUp = function() {

    isDrawing = false;

    };

    Mouse.addListener(mouseListener);

  5. Select Control > Test Movie to test the document.

  6. Drag your pointer to draw a line on the Stage.

  7. Click the button to erase what you've drawn.
     

Creating runtime data bindings using ActionScript 

TOP

If you use components to create applications, it's often necessary to add bindings between those components so that you can interact with data or have components interact with each other.

Interaction between components is necessary for creating usable forms or interfaces that your users can interact with. You can use the Bindings tab in the Component inspector to add bindings between components on the Stage. You can use the Bindings tab in the Component inspector to bind data between components on the Stage.

For more information on using the Bindings tab, see Working with bindings in the Bindings tab (Flash Professional only) in Using Flash. You can also find additional information in the following online articles: Building a Tip of the day Application (Part 2), Data Binding in Macromedia Flash MX Professional 2004, and Building a Google Search Application with Macromedia Flash MX Professional.

You can use ActionScript instead of the Bindings tab to create bindings between components. Adding code is often faster and more efficient than relying on the authoring environment. Using ActionScript to create bindings is necessary when you use code to add components to an application. You can choose to use the createClassObject() method to add components onto the Stage dynamically; however, you couldn't use the Bindings tab to create a binding because the components don't exist until runtime. Using ActionScript to add data binding is often called runtime data binding.

 

Creating bindings between UI components using ActionScript

TOP

It isn't difficult to bind data between two components at runtime. You can do so in Flash Basic 8 or Flash Professional 8. You must remember to include the DataBindingClasses component in your document for it to work, because that component contains the classes that you need to work with.

To create a binding between two TextInput components using ActionScript:

  1. Create a new Flash document called panel_as.fla.

  2. Drag two copies of the TextInput component onto the Stage.

  3. Give the components the following instance names: in_ti and out_ti.

  4. Select Window > Common Libraries > Classes and open the new common library called Classes.fla.

  5. Drag a copy of the DataBindingClasses component into the Library panel, or drag the component onto the Stage and then delete it.

    You can close the common library after you finish. After you delete the DataBindingClasses component from the Stage, Flash leaves a copy in the library.

    TIP : If you forget to delete the DataBindingClasses component from the Stage, the component's icon is visible at runtime.

    NOTE : When you created a binding using the Component inspector in the previous example, Flash added the DataBindingClasses component automatically to the FLA file. When you useActionScript to create data bindings, you must copy that class into your library yourself, as shown in the following step.

  6. Insert a new layer and name it actions.

    Add the following ActionScript to Frame 1 of the actions layer:

    var src:mx.data.binding.EndPoint = new mx.data.binding.EndPoint();

    src.component = in_ti;

    src.property = "text";

    src.event = "focusOut";

    var dest:mx.data.binding.EndPoint = new mx.data.binding.EndPoint();

    dest.component = out_ti;

    dest.property = "text";

    new mx.data.binding.Binding(src, dest);

    If you prefer the somewhat shortened version, you could import the binding classes and use the following code instead:

    import mx.data.binding.*;

    var src:EndPoint = new EndPoint();

    src.component = in_ti;

    src.property = "text";

    src.event = "focusOut";

    var dest:EndPoint = new EndPoint();

    dest.component = out_ti;

    dest.property = "text";

    new Binding(src, dest);

    This ActionScript creates two data binding end points, one for each component that you're binding. The first endpoint you create defines which component it is binding from (in_ti), which property to watch for (text), and which event will trigger the binding (focusOut). The second endpoint you create lists only the component and property (out_ti and text, respectively). Finally, you create the binding between the two endpoints when you call the constructor for the Binding class (new Binding(src, dest)).

    You don't need to use fully qualified class names (such as mx.data.binding.EndPoint) in your ActionScript, as you saw in the first code snippet. If you use the import statement at the beginning of your code, you can avoid using fully qualified names. When you import all the classes in the mx.data.binding package using the wildcard (*) (the package includes both the EndPoint and Binding classes), you can shorten your code and directly reference the EndPoint and Binding classes. For more information on import statements, see the import entry in the ActionScript 2.0 Language Reference.

  7. Select Control > Test Movie to test the code in the test environment. Enter some text into the in_ti text input field.

    After the in_ti instance loses focus (click the Stage, press Tab, or click the second field), Flash copies any text that you input into in_ti to the out_ti text field.

  8. Select File > Save to save your changes.

If you want to modify the text in the out_ti text input field from the previous exercise, your code can become a lot more complex. If you use the Component inspector to set up bindings, by default you create a two-way connection. This means that if you change either text field on the Stage, the other text field changes as well. When you use ActionScript to create bindings, your application works the opposite way. Runtime data bindings are one-way by default unless you specify otherwise, as demonstrated in the following example.

To use ActionScript to create a two-way binding, you need to make some small modifications to the code snippets from the previous procedure. This example uses the second, shortened ActionScript snippet from step 7.

To create a two-way binding:

  1. Open panel_as.fla from the previous example.

  2. Modify your ActionScript slightly (see boldface code) to match the following ActionScript:

    import mx.data.binding.*;

    var src:EndPoint = new EndPoint();

    src.component = in_ti;

    src.property = "text";

    src.event = "focusOut";

    var dest:EndPoint = new EndPoint();

    dest.component = out_ti;

    dest.property = "text";

    dest.event = "focusOut";

    new Binding(src, dest, null, true);

    The two changes you make to the ActionScript do the following:

  3. Define an event property for the destination EndPoint instance.

  4. Define two additional parameters for the Binding constructor.

    You use the first parameter for advanced formatting options; you can set that value to null or undefined. The second parameter defines whether the binding is two-way (true) or one-way (false).

    You might wonder where the focusOut event comes from. That's where the ActionScript becomes complicated. You can investigate the TextInput class and use some of the listed methods (such as change() or enter()), but you won't find the focusOut event there. The TextInput class inherits from the UIObject and UIComponent classes. If you view the UIComponent class, which adds focus support to components, you see four additional events: focusIn, focusOut, keyDown, and keyUp. You can use these events with the TextInput component.

  5. (Optional) If you want the previous example to update the value in the out_ti text input field, you can change the event from focusOut to change.

  6. Select Control > Test Movie to test the document.

Flash changes the second value in the in_ti text input field and updates the value for out_ti. You successfully created a two-way connection.

You can use the Binding classes with most user interface components of version 2 of the Macromedia Component Architecture, not just the TextInput component. The following example demonstrates how to use ActionScript to bind CheckBox instances and Label components during runtime.

To use binding classes with the CheckBox component:

  1. Create a new Flash document.

  2. Select File > Save As and name the new file checkbox_as.fla.

  3. Select Window > Common Libraries > Classes.

  4. Drag a copy of the DataBindingClasses class into the document's library.

  5. Drag a copy of the CheckBox component onto the Stage and give it the instance name my_ch.

  6. Drag a copy of the Label component onto the Stage and give it the instance name my_lbl.

  7. Create a new layer and name it actions.

  8. Add the following ActionScript to Frame 1 of the actions layer:

var srcEndPoint:Object = {component:my_ch, property:"selected", event:"click"};

var destEndPoint:Object = {component:my_lbl, property:"text"};

new mx.data.binding.Binding(srcEndPoint, destEndPoint);

You use objects to define the endpoints instead of creating new instances of the EndPoint class, as demonstrated in the previous exercises in this section. The code snippet in this step creates two objects, which act as endpoints for the binding. You create the binding when you call the constructor for the Binding class. To reduce the amount of code (and readability) even more, define the objects inline as shown in the following snippet:

new mx.data.binding.Binding({component:my_ch, property:"selected", event:"click"}, {component:my_lbl, property:"text"});

This ActionScript reduces the readability of your code, but it also reduces the amount of typing you have to do. If you share your FLA (or ActionScript) files, you might want to use the first snippet of ActionScript, because it is more reader friendly.
 

Using components, bindings, and custom formatters

TOP

Custom formatters help you format complex data in a specific way. You can also use custom formatting to help display images, HTML formatted text, or other components within a component such as the DataGrid. The following example illustrates how useful custom formatters can be.

To use custom formatters in a document:

  1. Create a new FLA file and add the DataBindingClasses class to the library (Window > Common Libraries > Classes).

  2. Drag a copy of the DateChooser component onto the Stage and give it the instance name my_dc.

  3. Drag a copy of the Label component onto the Stage and give it the instance name my_lbl.

  4. Insert a new layer and name it actions.

  5. Add the following ActionScript code to Frame 1 of the actions layer:

    import mx.data.binding.*;

    var src:EndPoint = new EndPoint();

    src.component = my_dc;

    src.property = "selectedDate";

    src.event = "change";

    var dest:EndPoint = new EndPoint();

    dest.component = my_lbl;

    dest.property = "text";

    new Binding(src, dest);

    This code creates a binding between the DateChooser's selectedDate property and the text property of the Label component on the Stage. Each time you click a new date in the calendar, the selected date appears in the Label component.

  6. Save the Flash document as customformat.fla in a convenient location on your hard disk.

    (You will recycle it in the next exercise.)

  7. Select Control > Test Movie to test the document.

    Try to change the dates in the Calendar component and you'll see the currently selected date appear in the Label component. The Label component isn't wide enough to display the entire date, so Flash crops off the text.

  8. Close the test SWF file and return to the authoring environment.

    Either resize the Label component on the Stage or select the Label component and set the autoSize property to left in the Parameters tab of the Property inspector.

  9. Select Control > Test Movie to test the document again.

Now the text field displays the entire date, although it is awkward and lacks formatting. Depending on your own time zone and selected date, the date might appear similar to this: Thu Nov 4 00:00:00 GMT-0800 2004

Even though the binding works properly and displays the selectedDate property, these dates aren't very user friendly. Nobody wants to see time-zone offsets, and you might not want to display hours, minutes, and seconds. What you need is a way to format the date so that it's more readable and a little less mechanical. Custom formatters are particularly useful for formatting text.

Formatting data using the CustomFormatter class

The CustomFormatter class defines two methods, format() and unformat(), that provide the ability to transform data values from a specific data type to String, and the reverse. By default, these methods do nothing; you must implement them in a subclass of mx.data.binding.CustomFormatter. The CustomFormatter class lets you convert data types to strings and back. In this case, you want to convert the selectedDate property from the DateChooser component into a nicely formatted string when the value copies into the Label component.

The following example shows you how to create your own custom formatter, which displays the date as NOV 4, 2004 instead of displaying a default date string.

NOTE : You need to complete the exercise from Using components, bindings, and custom formatters before you begin this one.

To format data using the CustomFormatter class:

  1. Select File > New and then select ActionScript File to create a new AS file.

  2. Select File > Save As and save the new file as DateFormat.as.

  3. Enter the following code into the Script window:

    class DateFormat extends mx.data.binding.CustomFormatter {

    function format(rawValue:Date):String {

    var returnValue:String;

    var monthName_array:Array = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];

    returnValue = monthName_array[rawValue.getMonth()]+" "+rawValue.getDate()+", "+rawValue.getFullYear();

    return returnValue;

    }

    }

    The first section of code defines the new class called DateFormat, which extends the CustomFormatter class in the mx.data.binding package. Remember that Flash compiles the binding classes in the DataBindingClasses component file, so you can't view them directly or find them within the Classes folder in the Flash install directory.

    The only method you use is the format() method, which converts the date instance into a custom string format. The next step is to create an array of month names so that the end result looks closer to NOV 4, 2004 rather than the default date format. Remember that arrays are zero-based in Flash, so if the value of rawValue.getMonth() returns 1, it represents February instead of January (because January is month 0). The remaining code builds the custom formatted string by concatenating values and returning the returnValue string.

    A problem can arise when you work with classes within a compiled clip, which you can see in the previous snippet. Because you extend a class that's located in the DataBindingClasses class and it isn't readily available to Flash, you encounter the following error when you check the syntax in the previous class:

    **Error** <path to DateFormat class>\DateFormat.as: Line 1: The class 'mx.data.binding.CustomFormatter' could not be loaded.

    class DateFormat extends mx.data.binding.CustomFormatter {

    Total ActionScript Errors: 1 Reported Errors: 1

    Your code is probably fine. This problem occurs when Flash cannot locate the class, and because of this, syntax checking fails.

  4. Save the DateFormat.as file.

  5. Open customformat.fla from the exercise in Using components, bindings, and custom formatters. Make sure you save or copy DateFormat.as in the same directory as this file.

  6. In customformat.fla, modify the ActionScript code in Frame 1 of the actions layer to match the following code:

    import mx.data.binding.*;

    var src:EndPoint = new EndPoint();

    src.component = my_dc;

    src.property = "selectedDate";

    src.event = "change";

    var dest:EndPoint = new EndPoint();

    dest.component = my_lbl;

    dest.property = "text";

    new Binding(src, dest, {cls:mx.data.formatters.Custom, settings:{classname:"DateFormat", classname_class:DateFormat}});

    This time you define a customFormatter object, which tells Flash that you're using the newly created DateFormat class to format the endpoint on the binding.

  7. Save the changes in your document and select Control > Test Movie to test your code.

Adding and binding components on the Stage

TOP

One of the biggest advantages to using the binding classes with ActionScript is that you can create bindings between components that Flash has added to the Stage at runtime. Imagine creating your own custom class that adds the appropriate text fields to the Stage at runtime, and then validates the necessary data and adds the necessary bindings. As long as you have the components in your library, you can add them dynamically and use a couple of extra lines of code to create bindings.

To add and then bind components on the Stage by using ActionScript:

  1. Create a new Flash document.

  2. Drag a ComboBox and a Label component into the document's library.

  3. Insert a new layer and name it actions.

  4. Add the following code to Frame 1 of the actions layer:

import mx.data.binding.*;

this.createClassObject(mx.controls.ComboBox, "my_cb", 1, {_x:10, _y:10});

this.createClassObject(mx.controls.Label, "my_lbl", 2, {_x:10, _y:40});

my_cb.addItem("JAN", 0);

my_cb.addItem("FEB", 1);

my_cb.addItem("MAR", 2);

my_cb.addItem("APR", 3);

my_cb.addItem("MAY", 4);

my_cb.addItem("JUN", 5);

var src:EndPoint = new EndPoint();

src.component = my_cb;

src.property = "value";

src.event = "change";

var dest:EndPoint = new EndPoint();

dest.component = my_lbl;

dest.property = "text";

new Binding(src, dest);

The first line of ActionScript imports the classes from the mx.data.binding package so that you don't need to use fully qualified paths in your code. The next two lines of ActionScript attach the components from the document's library to the Stage. Next you position the components on the Stage.

Finally you add data to the ComboBox instance and create the binding between the my_cb ComboBox and my_lbl Label component on the Stage.
 

Deconstructing a sample script

TOP

In the sample SWF file zapper.swf, when a user drags the bug to the electrical outlet, the bug falls and the outlet shakes. The main timeline has only one frame and contains three objects: the ladybug, the outlet, and a reset button. Each object is a movie clip instance.

The following script is attached to Frame 1 of the main Timeline:

var initx:Number = bug_mc._x;

var inity:Number = bug_mc._y;

var zapped:Boolean = false;

reset_btn.onRelease = function() {

zapped = false;

bug_mc._x = initx;

bug_mc._y = inity;

bug_mc._alpha = 100;

bug_mc._rotation = 0;

};

bug_mc.onPress = function() {

this.startDrag();

};

bug_mc.onRelease = function() {

this.stopDrag();

};

bug_mc.onEnterFrame = function() {

if (this.hitTest(this._parent.zapper_mc)) {

this.stopDrag();

zapped = true;

bug_mc._alpha = 75;

bug_mc._rotation = 20;

this._parent.zapper_mc.play();

}

if (zapped) {

bug_mc._y += 25;

}

};

The bug's instance name is bug_mc, and the outlet's instance name is zapper_mc. In the script, the bug is referred to as this because the script is attached to the bug and the reserved word this refers to the object that contains it.

There are event handlers with several different events: onRelease(), onPress(), and onEnterFrame(). The event handlers are defined on Frame 1 after the SWF file loads. The actions in the onEnterFrame() event handler executes every time the playhead enters a frame. Even in a one-frame SWF file, the playhead still enters that frame repeatedly and the script executes repeatedly.

Two variables, initx and inity, are defined to store the initial x and y positions of the bug_mc movie clip instance. A function is defined and assigned to the onRelease event handler of the reset_btn instance. This function is called each time the mouse button is pressed and released on the reset_btn button. The function places the ladybug back in its starting position on the Stage, resets its rotation and alpha values, and resets the zapped variable to false.

A conditional if statement uses the hitTest() method to check whether the bug instance is touching the outlet instance (this._parent.zapper_mc). The two possible outcomes of the evaluation are true or false:

  • If the hitTest() method returns true, Flash calls the stopDrag() method, sets the zapper_mc variable to true, changes the alpha and rotation properties, and instructs the zapped instance to play.

  • If the hitTest() method returns false, none of the code within the curly braces ({}) immediately following the if statement runs.

The actions in the onPress() statement execute when the mouse button is pressed over the bug_mc instance. The actions in the onRelease() statement execute when the mouse button is released over the bug_mc instance.

The startDrag() action lets you drag the ladybug. Because the script is attached to the bug_mc instance, the keyword this indicates that the bug instance is the one you can drag:

bug_mc.onPress = function() {

this.startDrag();

};

The stopDrag() action stops the drag action:

bug_mc.onRelease = function() {

this.stopDrag();

};

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash