Event Handlers Applied
We'll conclude our exploration of ActionScript events and event handlers with a few real-world examples. These are simple applications, but they give us a sense of how flexible event-based developing can be. The last two examples are available for download from the online Code Depot.
Example 10-7 makes a clip shrink and grow.
Example 10-7. Oscillating the Size of a Movie Clip
onClipEvent (load) {
var shrinking = false; var maxHeight = 300; var minHeight = 30;
}
onClipEvent (enterFrame) {
if (_height < maxHeight && shrinking == false) {
_height += 10; _width += 10;
}
else {
shrinking = true;
}
if (shrinking == true) {
if (_height > minHeight) {
_height -= 10; _width -= 10;
}
else {
shrinking = false; _height += 10; // Increment here so we don't _width += 10; // miss a cycle
}
} }
Example 10-8 simulates a custom mouse pointer by hiding the normal system pointer and making a clip follow the mouse location around the screen. In the example, the mouseDown and mouseUp handlers resize the custom pointer slightly to indicate mouseclicks.
Example 10-8. A Custom Mouse Pointer
onClipEvent (load) {
Mouse.hide( );
}
onClipEvent (mouseMove) {
_x = _root._xmouse; _ y = _root._ymouse; updateAfterEvent( );
}
onClipEvent (mouseDown) {
_width *= .5; _height *= .5; updateAfterEvent( );
}
onClipEvent (mouseUp) {
_width *= 2; _height *= 2; updateAfterEvent( );
}
Finally, simply to prove the power of the ActionScript movie clip event handlers, Example 10-9 turns a movie clip into a customized button using mouseMove to check for rollovers, mouseDown and mouseUp to check for button clicks, and the hitTest( ) function to make hit detection a snap. This example assumes that the clip with the handlers has three keyframes labeled up, down, and over (corresponding with the usual button states).
Example 10-9. A Movie Clip Button
onClipEvent (load) {
stop( );
}
onClipEvent (mouseMove) {
if (hitTest(_root._xmouse, _root._ymouse, true) && !buttonDown) {
this.gotoAndStop("over");
}
else if (!hitTest(_root._xmouse, _root._ymouse, true) && !buttonDown) {
this.gotoAndStop("up");
}
updateAfterEvent( );
}
onClipEvent (mouseDown) {
if (hitTest(_root._xmouse, _root._ymouse, true)) {
buttonDown = true; this.gotoAndStop("down");
}
updateAfterEvent( );
}
onClipEvent (mouseUp) {
buttonDown = false; if (!hitTest(_root._xmouse, _root._ymouse, true)) {
this.gotoAndStop("up");
}
else {
this.gotoAndStop("over");
}
updateAfterEvent( );
}