Main Content

You are here:

Events in AS3

Hello and welcome. Here is how we left the circle last time:

package{
        import flash.display.*;
        public class graphical extends MovieClip{
                public var mc1:MovieClip = new MovieClip();
                public function graphical(){
                        mc1.graphics.lineStyle(1);
                        mc1.graphics.beginFill(0xff0000); 
                        mc1.graphics.drawCircle(200,200,50);
                        this.addChild(mc1);mc1.graphics.endFill();
                }
        }
}

Last time we only needed the flash.display library, now we need to handle events as well, so underneath the previous import, add:

import flash.events.*;

In AS2, we could use the onClipEvent(enterFrame) to do stuff with the circle. To give the circle some actions this time however, we use a different method. Just before the this.addChild line, add this line:

mc1.addEventListener("enterFrame",enterFrame_handler);

that is: addEventListener("Event",function to do);

You see, enterFrame is an event. A listener will test for an event. So the mc1 Movie Clip will test to see when the enterFrame event happens, and, when it does, it will do the enterFrame_handler function. A handler is what happens when an event happens, we just use a name. Now we have to put in the event handler.

After one of the }s, before two of them, we will put in the event handler:

private function enterFrame_handler(e:Event):void{
                                mc1.alpha = mc1.alpha - 0.01;
}

private means we can't call this function by any other means. "e:Event" is standard for this type of event. void means nothing: this function won't return anything. Now, on enterFrame, the alpha of the circle will decrease: it will become more transparent. Save, go to the project file and compile it by pressing "Test Project".

You should see the same circle we made last time, but this time it will become fainter and fainter: the basis for onClipEvent(enterFrame) is complete! Pat yourself on the back, but we still have lots of other things to do. See you for them,

Harry.

Comments

Finished code:

package {
import flash.display.*;
import flash.events.*;
        public class graphical extends MovieClip {
                public var mc1:MovieClip = new MovieClip();
                public function graphical() {
                        mc1.graphics.lineStyle(1);
                        mc1.graphics.beginFill(0xff0000);
                        mc1.graphics.drawCircle(200,200,50);
                        mc1.addEventListener("enterFrame",enterFrame_handler);
                        this.addChild(mc1);mc1.graphics.endFill();
                }
                private function enterFrame_handler(e:Event):void {
                        mc1.alpha = mc1.alpha - 0.01;
                }
        }
}