Saturday, April 14, 2012

AS3.0 Adding Double Click Event

“Double clicking” I felt is quiet difficult in AS2. We had to add timer event and then, in that time interval had to click on the object. As a developer this was really brain teasing game as we had to decide what time should be given.

Now in AS3 it has got something easy and we don’t have to care about what time. It’s already defined somewhere for us and we just have add event of double clicking.


Lets create a button first. We can use movie clip for events so with text “Play” we will create it on the stage at required place for instance we will assume it as Frame One on timeline. Name it as “Play_btn”. Add a layer above it and add
stop(); action.


Add another frame to timeline by pressing “F7”. On this frame we will add our animation. Create an animation whatever you like; motion tween, shape tween etc.


Now our scripting part starts;

Select the button movie clip “Play_btn”.

Add an instance name “DCButton(Double Click Button) to it.

Now we have to enable double click event for our button. So let’s add following script;


DCButton.doubleClickEnabled = true;

This enables the double click action for that button instance.

 Next step is adding an event listener which will enable flash to call the function on double click event.


DCButton.addEventListener( MouseEvent.DOUBLE_CLICK, playAnim );

Here “playAnim” is the name of function which will be called to play the animation from next frame.


Let’s add a function;


function playAnim(e:MouseEvent):void
{
            play();
}


When you will add Mouse Event, flash will add a line above the script to import mouse events;

import flash.events.MouseEvent;

If it does not add it, please add it.

Test your movie.

This is your code until now;


import flash.events.MouseEvent;
stop();
DCButton.doubleClickEnabled = true;
DCButton.addEventListener( MouseEvent.DOUBLE_CLICK, gotoNextFrame );
function gotoNextFrame(e:MouseEvent):void
{
            play();
}


Sometimes, your buttons may have objects inside it which may be helping your GUI to look alive. But these objects may register the click event and their parent movie clip may not. This will lead you to unwanted results. We can just disable these objects from receiving the mouse event by adding following line to your code;

DCButton.mouseChildren = false;

Your complete script will look like;


import flash.events.MouseEvent;
stop();
DCButton.mouseChildren = false;
DCButton.doubleClickEnabled = true;
DCButton.addEventListener( MouseEvent.DOUBLE_CLICK, gotoNextFrame );
function gotoNextFrame(e:MouseEvent):void
{
            play();
}

Test your movie.



Thanks..

No comments: