dimanche 22 janvier 2017

Actionscript 3 - One event listener with multiple occurances

I have a sound effect that is being triggered every time an object gets hit in my game. This effect could be triggered one time, 10 times, 30 times, or anywhere in between. This all works just fine and was never a problem... until I decided that I wanted the sounds to finish playing before the next round could begin. So I put in an addEventListener every time the sound was called on to play and added a boolean flag saying it was playing. Once it was done I removed the listener and changed the boolean flag back to false. Something like this:

internal function boomSound():void {
    _sfxChannel = _goBoom.play(25);
    _sfxChannel.addEventListener(Event.SOUND_COMPLETE, boomSoundFinished, false, 0, true);

internal function boomSoundFinished(event:Event):void {
    _sfxChannel.removeEventListener(Event.SOUND_COMPLETE, boomSoundFinished);

However, this lead to a problem because I didn't have unique events happening. So when the first boom finished, the eventListener would fire and remove itself. But if a second boom had started before the first was done, it was again adding the same eventListener which was getting removed by the first boom finishing. So now the 2nd boom didn't have an event listening for it anymore. And then maybe a third, forth, fifth would occur and maybe get a complete event, or maybe not. This lead to _boomPlaying=false even if there was still a boom playing.

So is there a way to make this work? I was thinking of something along the lines of an array to store the events and giving them a different number each time it's triggered, and then removing them in the remove function... but that seems like a pretty complicated solution. I was reading about event.currentTarget but when I try to trace that I'm just getting the reference to the SoundChannel and event.currentTarget.name gives an error because I haven't set a name up. Can anyone point me in the right direction here please? Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire