0 votes

I am trying to get a sound effect to play once when my object is at a certain position, I'm using a AudioStreamPlayer2D for my audio. The audio is Not assigned to loop.
Thank You!

Here is my code

extends KinematicBody2D


var move = Vector2()

func _physics_process(delta):
    if position.y > 328:
        move.y = -50
    else:
        move.y = 0
        $Audio.play()
    move = move_and_slide(move)
asked May 12 in Engine by CreekWorks (36 points)

1 Answer

+1 vote
Best answer

Generally, you'd use a boolean variable to accomplish that. However, you say you want to play it once, but I assume you really want to play it more than once in the entire game...

To really play it once you can do something like:

extends KinematicBody2D

var move = Vector2()
var sound_has_played = false

func _physics_process(delta):
    if position.y > 328:
        move.y = -50
    else:
        move.y = 0
        if !sound_has_played:
            sound_has_played = true
            $Audio.play()
    move = move_and_slide(move)

This just plays the sound if it hasn't been played yet. Then, once the sound is played, it sets a boolean so it won't play again. If you do want to play it again later, you'll need to set the sound_has_played back to false as appropriate to allow the sound to play again.

answered May 12 by jgodfrey (5,574 points)
selected May 12 by CreekWorks

Thank You! I wanted to play it once and only once because it is on the title screen and is for text that pops up once. Thank you again!

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.