I’ve got a small sprite that is the “smoke trail” behind a missile in a flash animation. I made a self-contained class to handle the creation and removal of itself:
public class Spark extends Sprite {
private var lifetime:Number = 15;
private var gfxRef:MovieClip = new fx_particleTrail();
private var canvas:Sprite;
public function Spark(x:Number, y:Number, to:Sprite) {
gfxRef.x = x;
gfxRef.y = y;
canvas = to;
canvas.addChild(gfxRef);
addEventListener(Event.ENTER_FRAME, tick);
}
private function tick(e:Event):void {
lifetime --;
gfxRef.alpha -= 0.05;
if (lifetime <= 0) {
gfxRef.alpha = 0;
removeEventListener(Event.ENTER_FRAME, tick);
canvas.removeChild(gfxRef);
gfxRef = null;
}
}
}
It all seems to work fine – I can’t trace any errors out of this routine. However, sometimes a spark will stick to the screen forever – the lifetime counter stalls at a certain number and never progresses. It is as if the EventListener just decided to give up the ghost.
I’m pretty sure it’s not initialization as they will fail in various states of Alpha-tude, indicating that there is a mass failure at some point or another.
I thought perhaps generating so many at once was a problem, but I rigged it to generate a single one – and I threw in some traces:
> Born
> 15
> 14
> 13
> 12
And it ends there. The event listener was placed and it just stopped for some reason!s
This is working with the FlexSDK in AS3/Notepad (not using the Flash development environment).
Help!
There is nothing immediately wrong with your code. I have a strong suspicion that the problem is not in the code you posted, but elsewhere. If I take your exact code and run it (while commenting out things related to gfx) it counts down to 0 as expected.
What is managing the Spark (or collection of sparks)? Are you sure the lifetime of each Spark instance is long enough?
Finally, your general approach is not very efficient. Having each Spark with its own event listener isn’t strictly necessary and you should consider a class that has a single update loop and manages all of the Sparks. Have a look at some existing particle systems like flint particles.