Jump to content

Play sound when key pressed


Strutyk
 Share

Recommended Posts

Hi all. I have a problem managing the ghost character. I need that when the left button is pressed - the character flies to the left up, and play fly sound. But when the right button is pressed while the left button is pressed, the character stopped and stopped playing fly sound.

if (this.leftKey.isDown) {
    //Play Fly sound, when LEFT key is pressed
    this.playFlySound();
    this.ghost.body.moves = true;
    this.ghost.body.velocity.x = -120;
    this.ghost.body.velocity.y = -160;
    //Stop Fly sound, when LEFT key is pressed & RIGHT key pressed to
    if (this.rightKey.isDown) {
        this.stopFlySound();
        this.ghost.body.moves = false;
        this.ghost.body.velocity.x = 0;
        this.ghost.body.velocity.y = 0;
    }
}

In my version of the code, the fly sound start play when the left button is released. Please help me with the problem.

Link to comment
Share on other sites

Does this work?:

if (this.leftKey.isDown) {
    if(this.rightKey.isDown)
    {
        this.stopFlySound();
        this.ghost.body.moves = false;
        this.ghost.body.velocity.x = 0;
        this.ghost.body.velocity.y = 0;
    }
    else
    {
        this.playFlySound();
        this.ghost.body.moves = true;
        this.ghost.body.velocity.x = -120;
        this.ghost.body.velocity.y = -160;
    }
}

 

Link to comment
Share on other sites

Looks like maybe you're restarting the sound's playback every frame until the the left key is released, at which point the sound is allowed to play through without restarting it every 16 ms (that's about how often your update function is called at 60 FPS). I'm guessing the fist 16 ms of the sound is inaudible due to a fade-in...

EDIT: Sorry I assumed that was an update handler for some reason, but if it's an input handler that gets called once per press then NM the above;)

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...