Deconstructing a sample script 589
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();
};