import flash.events.KeyboardEvent; import Particle; // Define our vector (just a dynamic array with a specied type in AS3!) var particleVect:Vector. = new Vector.; // Define our number of particles to display on the screen and a start/stop animation flag var numberOfParticles:uint = 200; function addParticles():void { // Create however many particles we've entered into our numberOfParticles variable for (var loop:uint = 0; loop < numberOfParticles; loop++) { // Create a new instance of Particle and add it to our Vector of Particles particleVect.push(new Particle()); // Randomise the x (horizontal) and y (vertical) locations on stage particleVect[loop].x = Math.random() * stage.stageWidth; particleVect[loop].y = Math.random() * stage.stageHeight; // Randomise alpha particleVect[loop].alpha = Math.random(); // Randomise size between 0% and 100% (i.e. between 0.0 and 1.0) var sizeScale:Number = Math.random(); particleVect[loop].scaleX = sizeScale; particleVect[loop].scaleY = sizeScale; // Add the particle to the stage addChild(particleVect[loop]); } // End of for loop } // End of addParticles function function removeParticles():void { // Remove however many particles we're working with from the stage for (var loop:uint = 0; loop < numberOfParticles; loop++) { // Call our custom destructor to unbind any particle eventListeners particleVect[loop].ParticleDestructor(); // Remove the particle from the stage removeChild(particleVect[loop]); } // Remove all but a single particle from the vector. // We cannot remove the last particle or it will completely destroy our global Particle vector // and if that happens, we cannot re-instantiate the global Particle vector from here when // (and if!) we want to resume animation! This is the same reason we can't just use "particleVect = null;"!! while(particleVect.length > 0) { particleVect.pop(); } } // End of removeParticles function function particleController(e:KeyboardEvent):void { // If the animation is stopped, add the particles and flip the flag if (toggleAnimation == false) { addParticles(); toggleAnimation = true; } else { // Otherwise animation must be running and we want it to stop, so remove the // particles and flip the flag removeParticles(); toggleAnimation = false; } } // End of particleController function // With all our functions in place, bind the particle controller function to a keypress stage.addEventListener(KeyboardEvent.KEY_DOWN, particleController); // Kick off the animation without waiting for keypress, but still allow a keypress to toggle the animation addParticles(); var toggleAnimation = true;