How can I have a sound play and repeat itself when a movement key is held and stops when you let go? I’m still relatively new with writing scripts, so any help is welcome.
Hi @butternyke,
You would first get a reference to the sound slot of your sound component, for example:
const slot = this.entity.sound.slot('footstep');
And then you can use the play/pause methods to control it’s playback. Make sure you set the sound slot in editor to loop (to make it continuous).
https://developer.playcanvas.com/en/api/pc.SoundSlot.html#play
Here is a simpler version of what he said:
in your game you can make a sound slot. you can “call” it so it listens to you after the const slot = this.entity.sound.slot('footstep');
and after this code (phrase) you can put if (this.app.keyboard.isPressed(pc.KEY_W)) { this.sound.slot('footstep').play; }
and then it should work. This is off the top of my head, so it MIGHT not work.
In the code editor, it states this:
'slot' is declared but its value is never read.
And when I launch the game, I can’t move and it gives this error:
Cannot read properties of undefined (reading 'slot')
Any ideas? All I can think of is changing this.sound.slot('footstep').play;
into this.entity.sound.play('footstep');
.
Looking at the manual, your suggestion should work.
this.entity.sound.play('footstep');
https://developer.playcanvas.com/en/api/pc.SoundComponent.html#play
I tried this and the sound only played/looped after I released the button.
It would be helpful if you share your code, because you probably have to change something.
The reason is probably that your sound is started repeatedly. Can you try the solution below?
if (!this.entity.sound.isPlaying('footstep')) {
this.entity.sound.play('footstep');
}
Apart from that, line 93 of your script is not needed in this case.
Thanks again!