0
votes

I am a complete newcomer to as3, having started about 3 months ago as part of a university project, so apologies if I am asking an obvious question or I provide the wrong information.

I am creating a game where a 'monster' from an array collides with a static movie clip which the user has to avoid by killing the monster before they get there.

When the monster reaches the movie clip, I want it to play a 'munch' sound once, then not play it again for a few seconds, but the code as it is means that the sound plays over and over again while the array item and movie clip collide, which does not sound right.

I tried to correct this by adding a timer which allows the sound to continue for half a second and then stops the sound channel, but this does not seem to have worked.

How can I make the sound play once, not play again for the next few seconds and then play again if the objects are still colliding?

Thanks in advance.

Heres my code:

var sc: SoundChannel;
var munch: Sound = new Sound(new URLRequest("audio/munch.mp3"));

var muteTest: Boolean = false;

var munchStop:Timer = new Timer (500, 1);
munchStop.addEventListener(TimerEvent.TIMER, afterMunchStop);
function afterMunchStop(event: TimerEvent): void {
sc.stop();
}

if (monster1Array[i].hitTestObject(centre_mc)) {
   if (muteTest == false) {
   sc = munch.play();
   munchStop.start();
}
1

1 Answers

0
votes
var sc: SoundChannel;
var munch: Sound = new Sound(new URLRequest("audio/munch.mp3"));
var soundIsPlaying: Boolean = false;

//sound should loop until objects no longer collide
var munchStop:Timer = new Timer(500);
munchStop.addEventListener(TimerEvent.TIMER, afterMunchStop);

addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(event:Event):void
{
    //play sound if monsters collide and sound is not already playing
    if (monster1Array[i].hitTestObject(centre_mc) && !soundIsPlaying)
    {
       sc = munch.play();
       soundIsPlaying = true;

       //start the timer if it's not running
       if(!munchStop.running)
           munchStop.start();
    } else {
       //stop the sound if it's playing
       if(sc)
           sc.stop();
       soundIsPlaying = false;

       //reset the timer when the objects are no longer colliding
       if(munchStop.running)
           munchStop.reset();
    }
}

function afterMunchStop(event: TimerEvent): void {
    soundIsPlaying = false;
}