+1 vote

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 physicsprocess(delta):

var speler = AudioStreamPlayer.new();
speler.stream = load("res://sfx/ShootGunMagnum.wav");

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"):
        speler.stream = load("res://sfx/ShootGunMagnum.wav");

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 physicsprocess(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?

asked Apr 8, 2019 in Engine by markwiering (13 points)

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.