Footsteps sound

I am trying to make a footsteps script on my game. I am trying to make it so that if you hold down W, A, S, or D, it will play a walking sound. However, I have two problems. One, it starts playing very delayed. Two, it continues playing even when I let go. This is my script:

    if(this.app.keyboard.isPressed(pc.KEY_W)) {
        pressed = true;
    } else {
        pressed = false;
    }
    
    
    if(this.app.keyboard.isPressed(pc.KEY_S)) {
        pressed = true;
    } else {
        pressed = false;
    }
    
    if(pressed === true) {
        this.entity.audiosource.play("walk");
    }

Hi @SkillsMasters!

A possible reason is a conflict in your script. For example you set the boolean pressed on false when the S key is not pressed while pressing on W is trying to set it on true.

I think you have to stop the audio in an else statement. Just like you start the audio you also have to stop the audio.

If I add this in:

    if(pressed === true) {
        this.entity.audiosource.play("walk");
    } else if (pressed === false) {
        this.entity.audiosource.stop();
    }

It doesn’t play anything at all. Currently, I edited my full script to just the W key for now.

    if(this.app.keyboard.isPressed(pc.KEY_W)) {
        pressed = true;
    } else {
        pressed = false;

    if(pressed === true) {
        this.entity.audiosource.play("walk");
    } else if (pressed === false) {
        this.entity.audiosource.stop();
    }

If I remove the last else if statement it plays but if I add it, it doesn’t play. I also tried making it just an else statement and that didn’t work either.

Does the sound effect have a delay in it? Can you show the project with the sound effect in please?

1 Like

Oh wait, I just realised you are playing the sound effect every frame. You will need to either check that it’s stopped before playing or keep track if you pressed the key last frame.

1 Like

Example: https://playcanvas.com/editor/scene/1147053

Press W to ‘walk’

2 Likes