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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.