![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | markwiering |
Hello there,
I am making a 2D cat game in the stable release of Godot 3.1, in which the cat begins to shoot when you press the “ui_select” (in my case, Left Control) key.
I want a certain .wav-file of a gunshot to be played whenever the player presses “ui_select”. I tried to implement this using the following code inside of func _physics_process(delta):
var speler = AudioStreamPlayer.new();
self.add_child(speler);
speler.stream = load("res://sfx/ShootGunMagnum.wav");
speler.play();
Then I moved up the “speler” variable, as not to re-initialise it at every frame, resulting in a code like this:
var speler = AudioStreamPlayer.new();
func _physics_process(delta):
if Input.is_action_pressed("ui_select"):
self.add_child(speler);
speler.stream = load("res://sfx/ShootGunMagnum.wav");
speler.play(true);
This yields an error, however: “ERROR: add_child: Can’t add child ‘@@3’ to ‘Speler’, already has a parent* ‘Speler’.
At: scene/main/node.cpp:1165”
Since func _physics_process(delta): is called every frame, having code that starts playing sound will just play the absolute beginning of the sound file and then, before having finished the end of the sound file, start itself over again, creating some kind of low beep rather than actual shot sounds.
- I am looking for a way to:
- Not to re-add a child countless of times; this is obviously not the desired behaviour.
- Implement some way to detect that a .wav-file is playing, so the .wav-file isn’t being started when it’s still playing.
The desired behaviour is to have the same .wav-file play itself over and over again as long as the “ui_select” button is pressed. If you release the button, the current .wav-file should finish (no interrupt!). If you simply press the “ui_select” button instead of keeping it pressed, the .wav-file should play once.
How do I do that?