John Lilley
John Lilley

Reputation: 159

ActionScript: Adding multiple instances of the same swf file to the stage

I'm creating a game in ActionScript 3.0 using the FlashPunk game engine and the FlashDevelop SDK. I've created my own MovieClip class that takes a preloaded movie clip file.

public function MyMovieClip(file:MovieClip, posX:int, posY:int, frameRate:int) 
    {
        movieClip = file;
        movieClip.x = posX;
        movieClip.y = posY;
        movieClip.stop();
        FP.stage.addChild(movieClip);


        timer = new Timer((1 / frameRate) * 1000);
        timer.start();
        timer.addEventListener(TimerEvent.TIMER, onTick);
    }

The update for my movie clip is as follows:

private function onTick(e:TimerEvent):void
    {
        if (isRepeating)
        {
            if (movieClip.currentFrame == movieClip.totalFrames )
            {
                movieClip.gotoAndStop(0);
            }
        }
        movieClip.nextFrame();
    }

The problem that I'm having is that when I have multiple instances of the MyMovieClip class using the same swf file, only the last instance is rendered and is updated for each instance of the class that I have.(e.g 3 instances of MyMovieClip, the last instance is updates at 3 times the speed.)

If anymore info is needed I'll be happy to supply it.

Upvotes: 1

Views: 1188

Answers (2)

You can create a new instance of the same loaded swf by doing this:

  // re-use a loaded swf
  var bytes:ByteArray = existingLoader.content.loaderInfo.bytes;
  var loader:Loader = new Loader();
  loader.loadBytes(bytes);

where existingLoader is the Loader that you used to load the swf in the first place.

The Loader used with loadBytes will dispatch another COMPLETE Event, so when you make a listener for that, you can use the 'cloned' version:

  loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWFClonedComplete);

Upvotes: 2

DanielB
DanielB

Reputation: 20230

You may have multiple instances of MyMovieClip, but what's with file:MovieClip which you are adding to the stage. If this is always the same instance of a MovieClip you will have this result, regardless how often you instantiate your MyMovieClip class, because you are adding the same instance multiple times to the stage.

You may have to load the "preloaded clip" multiple times or, if you are able to (you know the class name etc.), create a new instance of the desired class with getDefinitionByName() from your loaded clip and attach this new instance.

Upvotes: 1

Related Questions