USING CLIP EVENTS


When a movie clip instance with attached scripts enters a scene, that scene can take on a new look, feel, and function through the use of clip events. These events allow actions to be triggered when an instance enters or leaves a scene, when the mouse moves around in the scene, as well as several other ways.

The following describes the various clip events as well as provides real-world analogies for their uses. Note that you can only use clip events with scripts attached to movie clip instances.

Presence: onClipEvent (load)

When someone or something enters a room or an area, there can be all kinds of ripple effects: People's demeanors can change; the environment can be affected in some way; even the person (or thing) entering the room can change as a result of what's going on inside. This event handler provokes a similar response by triggering a script when a movie clip instance enters a scene useful for initializing the movie clip, for having it be affected by the environment it's entering, or for having it affect the environment.

Absence: onClipEvent (unLoad)

If a movie clip instance can affect a scene when it enters, it can also affect the scene when it leaves (sometimes in the opposite way). You can use this event handler to trigger a script when a movie clip instance exits a scene.

Power, energy: onClipEvent (enterFrame)

When an object is given energy or power, it usually signifies that it is taking action on a continual basis. Look at a clock; without power it sits motionless and useless. If you provide power to it, it begins ticking, the hands on the face begin moving and you're able to use it to tell time. This event handler is used to trigger a script continually, at the same rate your movie plays. If your movie's frame rate is set to 20 frames per second, the scripts this event handler triggers are executed 20 times a second. There are many powerful applications for this event handler, as you'll learn throughout this book.

Movement: onClipEvent (mouseMove)

Think of this event as a motion detector within your movie. If a movie clip instance is present in the scene to which this clip event is attached, a set of actions can be executed each time the user moves the mouse (even just a pixel). This allows you to create motion-related interactivity for example, the ability to detect movement direction (right, left, up, and down), current mouse position, and more.

Computer-based interaction: onClipEvent (mouseDown), onClipEvent (mouseUp), onClipEvent (keyDown), onClipEvent (keyUp)

Because the mouse and keyboard are designed to interact with computers, these clip events don't really have real-world equivalents. They do, however, provide a means of executing scripts when specific keys or the mouse button are pressed (or released). Although these events may seem similar to the press , release , and keyPress mouse events described earlier in this lesson, they're actually a bit more powerful. Using the keyUp and keyDown clip events, you can create key combinations, or keyboard shortcuts, in your application so that action is taken when a sequence of keys are pressed. In contrast, the keyPress mouse event allows for only a single key to initiate action. The mouseUp and mouseDown clip events are different than the press and release mouse events because while the latter only triggers scripts when the user interacts directly with a button, the mouseDown and mouseUp events trigger scripts when the mouse is pressed or released anywhere on the stage.

Receiving instructions: onClipEvent (data)

In real life, incomplete instructions can lead to all sorts of problems. The same holds true in Flash. Because Flash lets you load various types of data (variables, external SWFs, JPGs) from external sources into movie clip instances, this event handler plays a vital role in that it triggers a script, attached to an instance, only after this data has been completely loaded into it from the source. In so doing, it prevents you from receiving the type of errors that result from incomplete instructions. You can use this event to re-execute actions (refresh) if data is loaded into the clip more than once.

This is a visual representation of how clip events are triggered. The down arrow represents the mouse button being pressed down; the up arrow represents it being released. The asterisk represents an occurrence of the event.

graphics/02fig19.gif

In the following exercise, we'll create a project that simulates a burglar being caught in the act. The burglar's presence (or absence) will determine how the scene plays, and the burglar himself will be programmed to respond to the environment in various ways using clip events.

  1. Open ClipEvents1.fla in the Lesson02/Assets folder. Open the Property inspector.

    graphics/02fig20.gif

    This project contains a single scene that includes seven layers, which are named according to their content. Take special note of the two frames with labels: The one labeled Clear represents the scene without the burglar, and the one labeled Burglar introduces the burglar into the scene. (Move the playhead between these frames to get a handle on this concept since it will be critical to the success of our project.) The burglar graphic is actually a movie clip instance named burglar, which will contain most of the scripts that control our movie's interactivity. (More on that in a bit.) The burglar movie clip instance is the only movie element that appears and disappears when navigating between these two frame labels; all other elements are constantly present. Let's look at those.

    At the top right of the stage are four buttons. The one that depicts the burglar with the international sign of No (red circle with a line through it) on top will eventually be set up to move the scene to the Clear frame, thus "removing" the burglar from the scene. The other three buttons Tiny, Small, and Normal will be used to dictate our burglar's size.

    Below these buttons is a light-green circle graphic. This is a movie clip instance named timer. We will program timer to spin when the burglar is in the scene, giving the sense that it's tracking time.

    Below the timer movie clip instance is a text field named timeAmount. Here, we will be incrementing a number as long as the burglar is present once again to give the sense that we're tracking time.

    Below this text field are two more text fields, one with an X beside it, the other with a Y. Since we'll be programming our burglar to follow the mouse as it moves around, these text fields named mouseXPosition and mouseYPosition, respectively will be used to display the current X and Y coordinates of the burglar movie clip instance as it moves.

    Below these text fields is our last text field. Named message, it will provide the current status of our environment ("All Clear," "ALERT!!" and so on).

    Our scene contains only two other elements both movie clip instances that need to be examined in depth to be understood.

  2. Double-click the small circle in the top left of the work area, just above the stage, to edit this movie clip in place.

    This movie clip has an instance name of siren. With its timeline visible, you can see that it's made up of three layers and two frame labels. At the frame labeled On there's a siren sound on the timeline. When this movie's timeline is sent to that frame label, the sound will play. This will be used to simulate an alarm being turned on. The other frame label on this timeline, Off, contains no sound; thus, when the timeline is sent to that frame, the alarm will cease playing.

  3. Return to the main timeline. On the Lights layer, press the Show Layer button (red X) to reveal a big black box that covers the entire stage. Double-click it to edit this movie clip in place.

    This movie clip has an instance name of lights. With its timeline visible, you can see that it's made up of four layers and five frame labels. This movie clip is used to simulate various light angles in the movie. We'll be scripting our project so that when the burglar moves to a particular area of the screen, the appropriate light will come on. For example, if he moves left, the left "light" will come on (frame labeled "left"). On the Sound layer, we've placed a sound at each one of the frame labels that gives the audio effect of a big switch being toggled (the light is turning on).

    graphics/02fig21.gif

    Now that the introductions are complete, it's time to start scripting!

  4. Return to the main timeline. On the Lights layer, press the Hide Layer button to hide the big black area that is the lights movie clip instance. With the Actions panel open, select Frame 1 on the Actions layer and attach the following script:

     message.text = "All Clear";  stop (); 

    The first action places the text "All Clear" in the message text field as soon as the movie plays. Also, whenever the timeline is sent back to this frame label, this action will executed again. Knowing this, we can deduce that whenever "All Clear" appears in the message text field, the main timeline is at Frame 1 and the burglar is not present. An understanding of this functionality will prove important in a moment.

    The next action stops the timeline from moving past this frame until we instruct it to.

  5. With the Actions panel open, select the Tiny button and attach the following script:

     on (release) {    if (message.text == "All Clear") {      size = 50;      gotoAndStop ("Burglar");    } else {      burglar._xscale = 50;      burglar._yscale = 50;    }  } 

    When this button is pressed then released, it will take one of two sets of actions, depending on whether the main timeline is on the frame labeled Clear (no burglar) or the one labeled Burglar (burglar is present.) In essence, this script says that if the message text field contains the text "All Clear" (which it will whenever the main timeline is on Frame 1 and the burglar is not present), set the value of the size variable to 50 and move the main timeline to the frame labeled Burglar. At this frame the burglar will be present. The size variable will eventually be used to set the size of the burglar when he first appears in the scene. If message does not contain "All Clear," these actions are ignored and the ones below them are executed instead. This will also mean that the main timeline is currently at the frame labeled Burglar and the burglar movie clip instance is present in the scene. If this is the case, these actions will scale the vertical and horizontal size of the burglar movie clip instance to 50 percent of its original size.

  6. With the Actions panel open, select the Small button and attach the following script:

     on (release) {    if (message.text == "All Clear") {      size = 75;      gotoAndStop ("Burglar");    } else {      burglar._xscale = 75;      burglar._yscale = 75;    }  } 

    This is just a variation of the script attached to the button in the preceding step. The only difference is that size is given a value of 75 and the two actions that scale the burglar movie clip instance (if present in the scene) scale it to 75 percent.

  7. With the Actions panel open, select the Normal button and attach the following script:

     on (release) {    if (message.text == "All Clear") {      size = 100;      gotoAndStop ("Burglar");    } else {      burglar._xscale = 100;      burglar._yscale = 100;    }  } 

    Once again, this is just a variation of the script attached to the button in the previous step. The only difference is that size is given a value of 100 and the burglar movie clip instance (if present) is scaled to 100 percent, or its original size.

  8. With the Actions panel open, select the No Burglar button and attach the following script:

     on (release) {    gotoAndStop ("Clear");  } 

    This button does one thing: moves the main timeline to the frame labeled Clear where, as you'll remember, the burglar movie clip instance does not exist. When the timeline is moved back to Frame 1, the actions we set up in Step 4 will be executed again.

    In summary, the Tiny, Small, and Normal buttons are used to make the burglar appear or to resize it. The button we just configured makes the burglar disappear.

    The rest of the scripting for our project will be placed on the burglar movie clip instance itself.

  9. With the Actions panel open and the main timeline at the frame labeled Burglar, select the burglar movie clip instance and attach the following script:

     onClipEvent (load) {    startDrag (this, true);    this._xscale = _root.size;    this._yscale = _root.size;    _root.lights.gotoAndStop("bottom");    _root.mouseXPosition.text = _root._xmouse;    _root.mouseYPosition.text = _root._ymouse;    _root.message.text = "ALERT!";  } 

    This set of actions is triggered when this movie clip first appears (loads), or when it reappears in the scene as a result of the timeline being moved to this frame. The first action causes the burglar movie clip itself (this ) to become draggable. The next two actions scale the movie clip's horizontal and vertical size based on the current value of the size variable (which exists on the root, or main, timeline). You'll remember that we set this variable with one of our three buttons (Tiny, Small, Normal). Thus, when one of the buttons is pressed, the following will happen: The size variable is set to a value of 50, 75, or 100 (depending on which button was pressed); the main timeline is sent to the frame containing this movie clip instance; and on loading, the value of the size variable is used to set the size of the burglar.

    The next action tells the lights movie clip instance to move to the frame labeled bottom. At this label it appears that light is shining from the bottom of the screen. This is just a default setting. We'll make the light movie clip instance a bit more dynamic in a moment.

    The next two actions display the mouse's current X and Y positions in the text fields on the root timeline (mouseXPosition and mouseYPosition, respectively).

    The last action displays the text "ALERT!" in the message text field on the root timeline to indicate that the burglar is now present.

    graphics/02fig22.gif

  10. Add this script just below where the current one ends:

     onClipEvent (enterFrame) {    _root.time++;    _root.timeAmount.text = _root.time;    _root.timer._rotation = _root.timer._rotation + 1;  } 

    Here, the enterFrame event is used to execute three actions which are executed 24 times a second because this type of event executes actions at the same rate that the movie plays.

    The first action uses a variable named time to hold the value of an incrementing number. Using the ++ operator, each time the enterFrame event occurs (24 times a second), the value of this variable is incremented by 1. This syntax is the same as writing the following:

     _root.time = _root.time + 1; 

    The next action is used to display the incrementing value of the time variable in the timeAmount text field.

    The last action rotates the timer movie clip instance by 1 degree 24 times a second. This will produce the effect of the timer being turned on while the burglar is present.

    graphics/02fig23.gif

    NOTE

    Since this script exists on the burglar movie clip instance, it will only execute while that instance is present in the scene.

  11. Add this script just below where the current one ends:

     onClipEvent (mouseMove) {    if (_root._xmouse > Number(_root.mouseXPosition.text) + 10) {      _root.lights.gotoAndStop("right");      _root.message.text = "Intruder is moving East";    } else if (_root._xmouse < Number(_root.mouseXPosition.text) - 10) {      _root.lights.gotoAndStop("left");      _root.message.text = "Intruder is moving West";    } else if (_root._ymouse > Number(_root.mouseYPosition.text) + 10) {      _root.lights.gotoAndStop("bottom");      _root.message.text = "Intruder is moving South";    } else if (_root._ymouse < Number(_root.mouseYPosition.text) - 10) {      _root.lights.gotoAndStop("top");      _root.message.text = "Intruder is moving North";    }      _root.mouseXPosition.text = _root._xmouse;      _root.mouseYPosition.text = _root._ymouse;  } 

    The actions in this script are triggered every time the mouse is moved. An if/else if statement compares the mouse's current position with its last known position, then acts accordingly. We'll examine the first comparison in the statement; having done that, the rest should be self-explanatory. Before we begin, it's important to note that the load event we set up a few steps ago contained two actions that set the text displayed in the mouseXPosition and mouseYPosition text fields based on the X and Y positions of the mouse when the burglar movie clip is loaded. We will now use those text values in the comparisons made in this script. Since the information displayed in the fields will be used in mathematical comparisons in our if/else if statement, their values have to converted to numbers using the Number() function mentioned in Lesson 1. Thus, the script sees them as numeric values rather than text values.

    The first part of this script states that if the current horizontal position of the mouse (_root._xmouse ) is greater than the value of mouseXPosition plus 10, two actions will be executed. By checking the mouse's current position against its last recorded position, we can determine which direction it's moving. For example, if the current horizontal position of the mouse (_root._xmouse ) is 300 and the previously recorded position (as displayed in the _root.mouseXPosition text field) was 200, we know the mouse has moved to the right. This is because 300 is further to the right than its last recorded position of 200. In this case, our script would trigger two actions: one to move the light movie clip instance to the frame labeled right (where the light appears to come from the right part of the stage) and one to display the message "The intruder is moving right" in the message text field. The if statement uses four comparisons to determine whether the mouse has moved right, left, up, or down.

    NOTE

    Keep in mind that although the mouse can move in two directions simultaneously (for example, up and right in a diagonal direction), our script gives single-direction movement precedence. This means that right-left movements are of higher priority than up-down movements. Thus, if the mouse moves both left and down, the script will detect only the left movement. The reason for this is that the if statement first looks to see if the mouse has moved right. If it has, the two actions for dealing with this are executed, but no other part of the if statement is executed. If the mouse hasn't moved right, that part of the if statement is ignored, and our script checks whether the mouse has moved left. If it has, the two actions for dealing with this are executed, but no other part of the if statement is executed. This same process continues when checking for down and up movements. In essence, once a movement in any single direction has been detected, the rest of the script is ignored. Since the if statement looks for right, left, down, and up movement in that order, if it detects right and left movements first, down and up movements won't matter.

    On a side note, you'll notice that in each comparison we add or subtract 10 from the value of mouseXPosition or mouseYPosition (whatever the case may be) so that the mouse must move at least 10 pixels from its last recorded position before any action will occur. If we didn't do this, the mouse's movement on screen would look like firecrackers going off that is, visually too intense!

    The last two actions of this script (placed just before the last curly brace in the script) record the current X and Y positions of the mouse so that the next time this script is executed (that is, when the mouse is moved), these values can be used in the comparison process of the if statement again. Since these values are placed in the mouseXPosition and mouseYPosition text fields, each time the mouse is moved and these values are updated, the changes are displayed in those fields as well.

    In essence, this script compares the current position of the mouse against its previously recorded position; takes appropriate action based on whether the mouse has moved left, right, up, or down; and records the mouse's current position for the next time the mouse is moved.

    graphics/02fig24.gif

  12. Add this script just below where the current one ends:

     onClipEvent (unload) {    _root.time = 0;    _root.timeAmount = _root.time;    _root.timer._rotation = 0;    _root.message.text = "All Clear";    _root.mouseXPosition.text = "";    _root.mouseYPosition.text = "" ;    _root.lights.gotoAndStop ("Off");  } 

    This script dictates what happens when this movie clip instance (burglar) is unloaded, or no longer in the scene (as a result of the main timeline moving to a frame where it doesn't exist). This occurs when the No Burglar button is clicked and the main timeline is moved to the Clear frame, which is actually Frame 1.

    The above actions restore the elements to their original state (that is, before the burglar appeared in the scene): The first one resets the time variable to 0; the next action sets what is displayed in the timeAmount text field to the value of time (making it 0 as well); the next action resets the rotation property of the timer movie clip instance to 0; the action after that displays "All Clear" in the message text field; the subsequent two actions clear the mouseXPosition and mouseYPosition text fields; and the last action moves the lights movie clip instance to the frame labeled Off. This turns the scene black again.

  13. Add this script just below where the current one ends:

     onClipEvent (mouseDown) {    this.gotoAndStop("right");    _root.message.text = "Intruder is confused";  } 

    When the mouse button is pressed anywhere on screen, these two actions are executed. The first sends the burglar movie clip instance (this ) to the frame labeled right. At this label the intruder appears to be looking to his right. In addition, a short audio clip plays of him saying, "Oh, no!" The second action causes the message text field to display "Intruder is confused."

  14. Add this script just below where the current one ends:

     onClipEvent (mouseUp) {    this.gotoAndStop("left");    _root.message.text = "Intruder is running";  } 

    When the mouse button is released anywhere on screen, these two actions are executed. The first sends the burglar movie clip instance (this ) to the frame labeled left. At this label the intruder appears to be looking to his left. The second action causes the message text field to display "Intruder is running."

  15. Add this script just below where the current one ends:

     onClipEvent (keyDown) {    _root.siren.gotoAndStop("on");    _root.message.text = "Backup has been called";  } 

    When any key is pressed, these two actions are executed. The first sends the siren movie clip instance to the frame labeled on, causing a siren to be heard. The second action causes the message text field to display "Backup has been called."

  16. Add this script just below where the current one ends:

     onClipEvent (keyUp) {    stopAllSounds ();    _root.siren.gotoAndStop("off");    _root.message.text = "Silent alarm activated";  } 

    When any key is released, these three actions are executed. The first stops all sounds, including the currently playing siren. The second action sends the siren movie clip instance to the frame labeled off (causing the siren to be turned off). And the last action causes the message text field to display "Silent alarm activated."

    NOTE

    Since the mouseDown/mouseUp and keyDown/keyUp clip events are attached to the burglar movie clip instance, none has any affect until that instance appears in the scene.

    The scripting of our project is now complete.

  17. Choose Control > Test Movie to test the functionality of our project.

    Press one of the buttons on the top right corner of the stage to make the burglar appear. When he appears, notice how the environment changes. Move him around to see what changes his movement provokes. Press the button to remove him and notice what happens. When the burglar is in the scene, press the mouse or the space bar on the keyboard. Most of our movie's interactivity depends on the burglar instance being present in the scene, showing how introducing a single instance into the scene can change its dynamics completely.

  18. Close the test movie and save your work as ClipEvents2.fla.

    This completes the exercise.



Macromedia Flash MX ActionScripting Advanced. Training from the Source
Macromedia Flash MX ActionScripting: Advanced Training from the Source
ISBN: 0201770229
EAN: 2147483647
Year: 2002
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net