Creating clickable movie clips in ActionScript 3.0
One of the biggest improvements in the ActionScript 3.0 language is the new event model. In previous versions of ActionScript, the event model may have differed slightly (or not so slightly) depending on which symbols you were using. A MovieClip's event model may have been different from a component or other class/symbol, but now, everything uses the EventDispatcher and addEventListener() method. For an example of the old versus new methods, look at the following example:
// AS2
this.createEmptyMovieClip("mc", this.getNextHighestDepth());
mc.beginFill(0xFF0000);
mc.moveTo(0, 0);
mc.lineTo(100, 0);
mc.lineTo(100, 80);
mc.lineTo(0, 80);
mc.lineTo(0, 0);
mc.endFill();
mc._x = 80;
mc._y = 60;
mc.onRelease = clickHandler;
function clickHandler():Void {
trace("You sunk my battleship!");
}
NOTE: This code often uses an anonymous method, such as: mc.onRelease = function():Void {...}.
In ActionScript 3.0, the same code could be rewritten as follows:
// AS3
var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF0000);
mc.graphics.drawRect(0, 0, 100, 80);
mc.graphics.endFill();
mc.x = 80;
mc.y = 60;
mc.addEventListener(MouseEvent.CLICK, clickHandler);
addChild(mc);
function clickHandler(event:MouseEvent):void {
trace("You sunk my battleship!");
}
If you test the following code, you'll notice that the shape on the Stage is clickable, although the mouse cursor doesn't show the hand icon. If you want the hand cursor to appear when your mouse is over the movie clip, add the following line of code before the call to the addEventListener() method:
mc.buttonMode = true;
Comments
I wonder why addChild() is necessary?
Posted by: childless | September 7, 2006 12:27 PM
childless,
This is the way that the new display model works in Actionscript 3. It can be a good thing or a bad thing depending on how you look at it.
deHaan,
Thanks for the quick hint on using the hand cursor, that was precisely what I was searching for! :)
Posted by: Kevin | February 25, 2007 10:19 AM
childless,
This is the way that the new display model works in Actionscript 3. It can be a good thing or a bad thing depending on how you look at it.
Posted by: sohbet | April 28, 2008 06:55 AM
Thanks a lot for sharing this with us! Clear, Effective and Helpful!
Posted by: Pathelin | May 8, 2008 09:03 PM
how to add frames to dynamically created movieclip
Posted by: sds | May 22, 2008 11:42 PM