Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

Converting code into a class

Converting code into a class

The following example creates an ActionScript class which encapsulates all the logic that makes a movie clip draggable. Now whenever a new instance of this class is created, the shape is automatically draggable without having to write additional code for each instance on the Stage:

  1. Create a new FLA file and save it to your hard drive as fancyBall.fla.
  2. Select File > New and choose ActionScript File to create a new AS file.
  3. Save the new ActionScript document as Ball.as in the same folder as fancyBall.fla (created in Step 1).
  4. Add the following code to the ActionScript document:

    package {
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    public class Ball extends MovieClip {
    public function Ball() {
    trace("ball created: " + this.name);
    this.buttonMode = true;
    this.addEventListener(
    MouseEvent.CLICK, clickHandler);
    this.addEventListener(
    MouseEvent.MOUSE_DOWN, mouseDownListener);
    this.addEventListener(
    MouseEvent.MOUSE_UP, mouseUpListener);
    }
    private function clickHandler(event:MouseEvent):void {
    trace("You clicked the ball");
    }
    function mouseDownListener(event:MouseEvent):void {
    this.startDrag();
    }
    function mouseUpListener(event:MouseEvent):void {
    this.stopDrag();
    }
    }
    }

    This code defines a new class called Ball, which extends the MovieClip class (now located in the flash.display package in ActionScript 3.0). Notice that you must explicitly import classes when you work with external ActionScript documents, unlike when you work with FLA files.

  5. Save and close the Ball.as document and then open the fancyBall.fla document.
  6. Use the Oval tool to create a circle on the Stage and convert it to a MovieClip symbol, following the steps from the previous examples.
  7. Right-click the symbol in the Library panel and select Linkage from the context menu.
  8. Select Export for ActionScript and type Ball in the Class text box.
  9. Click OK to apply the changes and close the dialog box.
  10. After making sure that an instance of the ball symbol is on the Stage, select Control > Test Movie to create a SWF file. When you click the mouse on the ball instance, notice that the mouse cursor changes to a hand cursor and the symbol is still draggable.

It gets better! The next example shows you how to create class instances dynamically.

Comments