Understanding ActionScript > Deconstructing a sample script
Deconstructing a sample scriptIn this sample movie, when a user drags the bug to the bug zapper, the bug turns black and falls and the bug zapper flashes. The movie is one frame long and contains two objects, the bug movie clip instance and the zapper movie clip instance. Each movie clip also contains one frame.
The bug and zapper movie clip instances on the Stage in frame 1
There is only one script in the movie; it's attached to the bug
instance, as in the Object Actions panel below:
The Object Actions panel with the script attached to the bug
instance
Both objects have to be movie clips so you can give them instance names in the Instance panel and manipulate them with ActionScript. The bug's instance name is bug
and the zapper's instance name is zapper
. 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 calls it.
There are two onClipEvent
handlers with two different events: load
and enterFrame
. The actions in the onClipEvent(load)
statement only execute once, when the movie loads. The actions in the onClipEvent(enterFrame)
statement execute every time the playhead enters a frame. Even in a one-frame movie, the playhead still enters that frame repeatedly and the script executes repeatedly. The following actions occur within each onClipEvent
handler:
onClipEvent(load) A startDrag
action makes the bug movie clip draggable. An instance of the Color object is created with the new
operator and the Color constructor function, Color
, and assigned to the variable zap
:
onClipEvent (load) { startDrag (this, true); zap = new Color(this); }
onClipEvent(enterFrame) A conditional if
statement evaluates a hitTest
action to check whether the bug instance (this
) is touching the bug zapper instance (_root.zapper
). There are two possible outcomes of the evaluation, true
or false
:
onClipEvent (enterFrame) { if (this.hitTest(_root.zapper)) { zap.setRGB(0); setProperty (_target, _y, _y+50); setProperty (_root.zapper, _alpha, 50); stopDrag (); } else { setProperty (_root.zapper, _alpha, 100); } }
If the hitTest
action returns true
, the zap
object created by the load
event is used to set the bug's color to black. The bug's y property (_y
) is set to itself plus 50
so that the bug falls. The zapper's transparency (_alpha
) is set to 50
so that it dims.
The stopDrag
action stops the bug from being draggable.
If the hitTest
action returns false
, the action following the else
statement runs and the bug zapper's _alpha
value is set to 100
. This makes the bug zapper appear to flash as its _alpha
value goes from an initial state (100) to a zapped state (50) and back to an initial state. The hitTest
action returns false
and the else
statements execute after the bug has been zapped and fallen.