Strutyk

Play sound when key pressed

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.

Share this post


Link to post
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;
    }
}

 

Share this post


Link to post
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;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.