Introduction to ActionScript Tutorial > Create commands and reuse code

 

Create commands and reuse code

ActionScript has actions that let you control a movie in specific ways. For example, the play action moves the playhead forward in the Timeline, and the loadMovie action loads another Flash movie into the Flash Player. Each of these actions instructs Flash to perform a certain task. You may want to create your own commands in your movies. For example, in puzzle.fla, you need a command to scramble the puzzle pieces. To figure out how to write such a command with ActionScript, you must determine each step required to scramble the puzzle pieces and determine which ActionScript elements can be used to achieve those goals.

First, the pieces must be spread out within a certain area on the Stage; each movie clip has an _x and _y property that you can use to set its position and a _rotation property that you can use to set its rotation. To place and rotate each piece randomly, you need to generate a random number to use in an expression. ActionScript has a built-in Math object with a random method that you can use for this purpose.

A command in ActionScript is called a function. A function is a script that you can use over and over again in a movie to perform a certain task. For example, in puzzle.fla, every time a user clicks a Scramble Pieces button, the function Scramble is run, or called. This function places the puzzle pieces in random positions on the Stage. Instead of rewriting that same script on each of the two Scramble Pieces buttons, the function is written, or declared, once and called from each button. To examine the Scramble function, select Frame 1 in the main Timeline and open the Actions panel. Scroll down the Script pane until you see the Scramble function.

You can think of a function as a machine that does extra work for you. The machine can produce different results depending on what you put into it. For example, if you put bananas in a blender, you get mashed bananas, not mashed peaches. The elements you pass to a function to work on are called parameters or arguments. Parameters are passed inside the parentheses that follow the function. For example, the function RotateDisplayOrDrag(whichPiece) is passed the name of a puzzle piece, and it operates only on that piece. Parameters allow you to reuse functions in many different situations.

Functions are usually declared in the first frame of a movie. In the puzzle.fla files, the functions are declared in Frame 1.