Coding MovieClips as Buttons in AS3

I would like to start off my posts with a simple one but really painful if you are used to AS2 - creating buttons in AS3.

I remember the good old days when you could just say, “Hey Actionscript, onRollOver = function(){ doThis!};”.

I digress… so I’m gonna keep this short and sweet.

If you want to do this:

myMc.onRollOver = function(){} myMc.onRollOut = function(){} myMc.onPress = function(){} myMc.onRelease = function(){}

it looks like this:

import  flash.display.MovieClip; import  flash.events.MouseEvent; myMc.addEventListener(MouseEvent.ROLL_OVER, onRollOverHandler); myMc.addEventListener(MouseEvent.ROLL_OUT, onRollOutHandler); myMc.addEventListener(MouseEvent.CLICK, onClickHandler); myMc.addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler); myMc.addEventListener(MouseEvent.MOUSE_UP, onReleaseHandler); // if you want a hand cursor myMc.buttonMode = true; myMc.useHandCursor = true; function onRollOverHandler(myEvent:MouseEvent){ trace(“Over”); } function onRollOutHandler(myEvent:MouseEvent){ trace(“Out”); } function onClickHandler(myEvent:MouseEvent){ trace(“I waited for Press AND Release!!!”); } function onPressHandler(myEvent:MouseEvent){ trace(“Press”); } function onReleaseHandler(myEvent:MouseEvent){ trace(“Release”); }

Let’s go over a few facts about the new button experience.
1) onRollOver is no longer used (which is probably why you are reading this in the first place).
2) In AS3, MovieClips do not act like buttons just because they have listeners, you have to tell them that they are buttons. (

mc.buttonMode = true

)
3) If you are getting this error:

ArgumentError: Error #1063: Argument count mismatch on… Expected 0, got 1.

You need to simply add anyEventVarYouLike:MouseEvent within the parentheses of your function - i.e. function

myRollOver(args:MouseEvent){}.

4) If you are getting this error:

1046: Type was not found or was not a compile-time constant: MouseEvent

Then you forgot

import flash.events.MouseEvent

.

5) If you are getting this error:

ReferenceError: Error #1056: Cannot create property buttonMode on flash.display.Bitmap.
at …

Then you need to put the bitmap inside of a MovieClip - so

var MC:MovieClip = new MovieClip();
MC.addChild(theBitmap);

That’s all for now. Please comment or email and I will update this as well as respond.

rob

del.icio.us Slashdot Digg Facebook Technorati Google Yahoo


About this entry