animationactionscript-3animate-cc

AS3 Particle Explosion


I'm coming from AS2 and having trouble converting to AS3. I'm trying to make an exploding particle using a movie clip but keep running into errors.

Here's the original AS2 script:

maxparticles = 200; //number of particles

i = 0; //counter, for "while" loop
while(i < maxparticles){
    newparticlename = "particle" + i; //creates a new name for a new particle instance
    particle.duplicateMovieClip(newparticlename, i); //duplicates our particle mc
    i++;
}

And here's my converted AS3 script:

var maxparticles = 200; //number of particles

var i = 0; //counter, for "while" loop
while(i < maxparticles){
    var newparticlename = "particle" + i; //creates a new name for a new particle instance
    particle.duplicateMovieClip(newparticlename, i); //duplicates our particle mc
    i++;
}

I keep getting problems here here:

particle.duplicateMovieClip(newparticlename, i);

Any help is greatly appreciated.


Solution

  • AS3 does things a bit differently. There is no such method as duplicateMovieClip and there's no such concept. AS3 manipulates the visual objects (MovieClips, Shapes, etc.) in a more object way: you can create and destroy them, you can keep them in memory to save for later, you can detach them from their respective parents and re-attach them somewhere else.

    In order to create multiple instances of the same object you do as the following:

    1. Create it as a MovieClip (not as Graphic) item in the project's Library.
    2. Assign it a class in the Library properties and name the class, for example, Particle. The base class should be MovieClip (it is default). I can't provide any screens but it shouldn't be difficult to figure out.
    3. Place the following code:

    (please also keep in mind it wasn't tested, but the concept should be right)

    // Allows the script to interact with the Particle class.
    import Particle;
    
    // Number of particles.
    var maxparticles:int = 200;
    
    // I imagine you will need to access the particles somehow
    // in order to manipulate them, you'd better put them into
    // an Array to do so rather then address them by their names.
    var Plist:Array = new Array;
    
    // Counter, for "while" loop.
    var i:int = 0;
    
    // The loop.
    while (i < maxparticles)
    {
        // Let's create a new particle.
        // That's how it is done in AS3.
        var P:Particle = new Particle;
        
        // The unique name for the new particle. Whatever you want it for.
        P.name = "particle" + i;
        
        // Enlist the newly created particle.
        Plist.push(P);
        
        // At the moment, the P exists but is not yet attached to the display list
        //  (or to anything). It's a new concept, there wasn't  such thing in AS2.
        // Let's make it a part of the display list so that we can see it.
        addChild(P);
        
        i++;
    }