Moving objects with code

Using ActionScript to move an object is similar to modifying an object's _alpha property, except that you instead modify the object's _x or _y property.

The following procedure animates a dynamically loaded JPEG image and slides it horizontally across the Stage.

To move an instance on the Stage by using code:

  1. Create a new Flash document called moveClip.fla.
  2. Change the frame rate of the document to 24 fps in the Property inspector.

    The animation is much smoother if you use a higher frame rate, such as 24 fps.

  3. Select Frame 1 of the Timeline, and add the following code to the Actions panel:
    // Create a movie clip instance.
    this.createEmptyMovieClip("img1_mc", 10);
    var mcl_obj:Object = new Object();
    mcl_obj.onLoadInit = function (target_mc:MovieClip):Void {
        target_mc._x = Stage.width;
        target_mc.onEnterFrame = function() {
            target_mc._x -= 3; // decrease current _x position by 3 pixels
            if (target_mc._x <= 0) {
                target_mc._x = 0;
                delete target_mc.onEnterFrame;
            }
        };
    };
    var img_mcl:MovieClipLoader = new MovieClipLoader();
    img_mcl.addListener(mcl_obj);
    // Load an image into the movie clip
    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img1_mc);
    

    This code example loads an external image from a remote web server and, when the image is fully loaded, animates it horizontally across the Stage. Instead of using an onEnterFrame event handler, you could use the setInterval() function to animate the image.

  4. Select Control > Test Movie to test the document.

    The image loads and then animates from the right side of the Stage to the upper-left corner of the Stage.

For information on using an onEnterFrame event handler or setInterval() function to animate the image, see Fading objects with code.

For a source sample of scripted animation in Flash, animation.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/Animation folder to access the sample.

For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/Galleries folder to access these samples:

These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file, which includes scripted animation.


Flash CS3


 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/main/00000957.html