Saturday, June 4, 2011

Flash AS3: Making your clickable Movieclip to show the Mouse Cursor


Moving on from Flash 8 to the latest version of Flash, which was 5.5, one might have encounter difficulties like the following. When you have created a Button with a 'Movieclip' type, you will realize that the button will not show the mouse cursor, even you have added all the Eventlisteners.


In as2, an individual will not encounter the following issue:
button1.onRelease = function(){
 //by adding a onRelease function on a Button or a Movieclip, the mouse cursor will appear automatically.
}

But in as3, you need more than adding just an EventListener:
//By adding this line, you will force the mouse cursor to appear on the 'MovieClip'.
button1.buttonMode = true;
//Adding a click event to a Movieclip or Button and point it to a function once the user trigger the event.
button1.addEventListener(MouseEvent.CLICK, clickEvent);

//This function will be triggered when the user clicks on the above button.
function clickEvent(event:Event){
 //Some actions to be done here.
}

After coding for a few years, I preferred using a function to bind the whole 'Button' and 'MovieClip' with the respective EventListeners
//Setup button1 of type 'MovieClip' with all the basic EventListener and show the mouse cursor
setupNormBtn(button1);
//Setup button2 of type 'Button' with all the basic EventListener
setupBasicBtn(button2);

//Function to call to setup the basic EventListeners of a MovieClip
function setupNormBtn(tempMc){
 tempMc.buttonMode = true;
 tempMc.addEventListener(MouseEvent.ROLL_OVER, rollOverEvent);
 tempMc.addEventListener(MouseEvent.ROLL_OUT, rollOutEvent);
 tempMc.addEventListener(MouseEvent.CLICK, clickEvent);
}

//Function to call to remove the basic EventListeners of a MovieClip
function killNormBtn(tempMc){
 tempMc.buttonMode = false;
 tempMc.removeEventListener(MouseEvent.ROLL_OVER, rollOverEvent);
 tempMc.removeEventListener(MouseEvent.ROLL_OUT, rollOutEvent);
 tempMc.removeEventListener(MouseEvent.CLICK, clickEvent);
}

//Function to call to setup the basic EventListeners of a Button
function setupBasicBtn(tempMc){
 tempMc.addEventListener(MouseEvent.CLICK, clickEvent);
}

//Function to call to remove the basic EventListeners of a Button
function killBasicBtn(tempMc){
 tempMc.removeEventListener(MouseEvent.CLICK, clickEvent);
}

//Function will be called when the user rollover a MovieClip
function rollOverEvent(event:MouseEvent){
 event.target.gotoAndStop("over");
}

//Function will be called when the user rollout a MovieClip
function rollOutEvent(event:MouseEvent){
 event.target.gotoAndStop("up");
}

//Function will be called when the user clicks on the MovieClip or Button
function clickEvent(event:MouseEvent){
 if(event.target == button1){
  //do actions for button1
  trace("button1");
 }else if(event.target == button2){
  //do actions for button2
  trace("button2");
 }
}

No comments:

Post a Comment