Functions

Functions

Flash CS4 ActionScript 3.0 Tutorial

 

How to Connect Events to Perform Operations with Flash ActionScript

 

 

The most common way Functions are used is with Events. An Event could be a mouse click or pressing a specific key on the keyboard. Once the event happens it calls up a Function. Functions can contain conditional statements, loops, timeline instructions, math calculations, etc.

Functions are also helpful if you wish to access the same calculation or statement at different points in the script. Functions that appear later in the timeline can be called up in prior code or keyframes. The code for a simple Function could be:

function clearBall () {

redBall_mc.alpha=.6

}

clearBall();

In this example the name of the Function is clearBall. When the Function is run, the redBall_mc alpha is cut to 60%. The clearBall(); statement causes the function to run.

In the example below, this function is connected to an Event. The Event occurs at the document's frame rate. In our case the frame rate was set to 20 fps, so the Event occurs 20 times per second which means the Function is run 20 times per second.

Tutorial Elements

Movie Symbol with instance name purpleShape_mc

 

Step One

Add a Movie Symbol to the stage. The registration point should be set to the center of the symbol. For information on setting the symbol registration point, see topic, Setting / Moving Object Registration Point.

Step Two

Select the symbol and assign it an instance name of purpleShape_mc.

Step Three

Add a layer above the current content layer and name it Actions.

Step Four

Open the ActionScript panel for your keyframe in the Actions layer by Option double-clicking (PC - Alt double-clicking) the keyframe

Step Five

Copy/Paste the following code in the ActionScript Panel:

addEventListener(Event.ENTER_FRAME, shapeRotate);

function shapeRotate(e:Event):void {

purpleShape_mc.rotation +=6;

}

Step Six

Click the Auto Format button to format the code

Step Seven

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter).

Dissecting the Code

The first line of the code says that we are going to run a function 20 times per second because that is the fla file's current frame rate. The name of the function is shapeRotate.

The next lines of code define the function. Each time the function is called, the shape moves 6 degrees in a clock-wise direction. The +=6 adds 6 more degrees to the shape's current rotation position each time the function is run.

Watch Those Function Names

A function name should not be repeated in your project. If duplicate a function name, you will see an error when you test your movie.

 

Lynda.com career skills