Saturday, January 8, 2011

AddEvent in AS3

In AS3, you can add various events to MovieClip(MC) or Button.. Some often-used events are :

  • MouseEvent.MOUSE_UP (when you release your mouse after clicking MC/button)
  • MouseEvent.MOUSE_DOWN (when you click your mouse on a MC/button)
  • MouseEvent.MOUSE_OVER (when you hover your mouse on a MC/button)
  • Event.ENTER_FRAME
ENTER_FRAME is used to control the movie clip using code. You can do for example :

  • Control the movement by manipulating movieClip's properties : x, y, width, height, scaleX, scaleY, rotation, alpha, etc.
  • Control AI in flash games. You can add various conditions, for example, you want the enemy to move toward the player.
Here is the function to addEvent :

function myAddEvent(targetMov, type:String, func:Function){
targetMov.addEventListener(type, func);
function targetRemoved(event){
//if a button or MC removed from stage, the event will be removed also
if(targetMov is SimpleButton){
//remove event for button sound here, if you wish
}
targetMov.removeEventListener(type, func);
targetMov.removeEventListener(Event.REMOVED_FROM_STAGE, targetRemoved);
targetMov = null;
}
if(targetMov is SimpleButton){
//add event for button sound here, if you wish
}
targetMov.addEventListener(Event.REMOVED_FROM_STAGE,targetRemoved);
}


Example how to use that :
First, make a button or movie clip, then give the instance name "instanceOfTheButton"..
Add these lines of code.. (don't forget to add above function also)




function buttonClicked(event){
trace("I'm clicked");
}
myAddEvent(instanceOfTheButton, MouseEvent.MOUSE_DOWN, buttonClicked);

function buttonEnterFrame(event){
trace("It's happening every frame rate of the movie");
}
myAddEvent(instanceOfTheButton, Event.ENTER_FRAME, buttonEnterFrame);


I suggest you to use addEvent wrapped in a function, like above code..
Because, by default, an event of movieClip/button is NOT removed when the movieClip/button removed from stage.. This makes a garbage in the memory, and sometimes causing a NULL error..

No comments:

Post a Comment