Initializing class properties

In the example presented in the second procedure under Assigning a class to a movie clip symbol, you added the instance of the Ball symbol to the Stage while authoring. As discussed in Adding parameters to dynamically created movie clips, you can assign parameters to clips you create at runtime by using the initObject parameter of attachMovie() and duplicateMovie(). You can use this feature to initialize properties of the class you're assigning to a movie clip.

For example, the following class named MoveRightDistance is a variation of the MoveRight class (see Assigning a class to a movie clip symbol). The difference is a new property named distance, whose value determines how many pixels a movie clip moves each time it is clicked.

To pass arguments to a custom class:

  1. Create a new ActionScript document and save it as MoveRightDistance.as.
  2. Type the following ActionScript into the Script window:
    // MoveRightDistance class -- moves clip to the right every frame.
    class MoveRightDistance extends MovieClip {
        // Distance property determines how many
        // pixels to move clip for each mouse press.
        var distance:Number;
        function onPress() {
            this._x += this.distance;
        }
    }
    
  3. Save your progress.
  4. Create a new Flash document, and save it as MoveRightDistance.fla in the same directory as the class file.
  5. Create a movie clip symbol that contains a vector shape, such as an oval, and then delete any content from the Stage.

    You only need a movie clip symbol in the library for this example.

  6. In the Library panel, right-click (Windows) or Control-click (Macintosh) the symbol and select Linkage from the context menu.
  7. Assign the linkage identifier Ball to the symbol.
  8. Type MoveRightDistance into the AS 2.0 Class text box.
  9. Add the following code to Frame 1 of the Timeline:
    this.attachMovie("Ball", "ball50_mc", 10, {distance:50});
    this.attachMovie("Ball", "ball125_mc", 20, {distance:125});
    

    This code creates two new instances of the symbol on the root timeline of the SWF file. The first instance, named ball50_mc, moves 50 pixels each time it is clicked; the second, named ball125_mc, moves 125 pixels each time it is clicked.

  10. Select Control > Test Movie to test the SWF file.