Search code examples
actionscript-3flashactionscriptadobe-animate

AS3 animate dynamically created movie clips with ENTER_FRAME


I have some code which loads a movie clip from the library, reproduces it and spreads it around the stage in different sizes, positions and rotations. What I can't figure out is how to then animate each one with an ENTER_FRAME event listener - So maybe I can also animate the scale, position and rotations? Any help greatly appreciated. Thanks.

for (var i = 0; i < 20; i++ )
{

    //Generate Item from library
    var MovieClip_mc:mcMovieClip = new mcMovieClip();
    addChild(MovieClip_mc);

    //Size
    var RandomSize = (Math.random() * 0.5) + 0.5;
    MovieClip_mc.scaleX = RandomSize;
    MovieClip_mc.scaleY = RandomSize;

    //Rotation
    var RandomRotation:Number = Math.floor(Math.random()*360);
    MovieClip_mc.rotation = RandomRotation;

    //Position
    MovieClip_mc.x = Math.floor(Math.random() * CanvasWidth);
    MovieClip_mc.y = Math.floor(Math.random() * CanvasHeight);

}

Solution

  • For performance benefits, it is better to do it using one ENTER_FRAME handler. The handler can be located in your main class and update each mcMovieClip's properties by calling certain methods declared in the mcMovieClip class. Below is a simple example.

    Main class

    var mcs:Array = [];
    for(var i:int = 0; i < 1; i++)
    {
        mcs.push(new mcMovieClip());
        addChild(mcs[i]);
    }
    addEventListener(Event.ENTER_FRAME, updateTime);
    
    function updateTime(e:Event):void
    {
        for(var j:int = 0; j < mcs.length; j++)
        {
            mcs[j].updatePosition(Math.random() * stage.stageWidth, 
                                  Math.random() * stage.stageHeight);
            mcs[j].updateRotation(Math.random() * 360);
            mcs[j].updateSize(Math.random());
        }
    }
    

    mcMovieClip class

    function updateSize(size:Number):void
    {
        this.scaleX = this.scaleY = size;
    }
    function updateRotation(rot:Number):void
    {
        this.rotation = rot;
    }
    function updatePosition(newX:Number, newY:Number):void
    {
        this.x = newX;
        this.y = newY;
    }