๐Ÿ”Š Coding the Sound Effects | myBetabox

๐Ÿ”Š Coding the Sound Effects

Keyboard Guide

Coding the Sound Effects

Let’s do something similar with these sound effects like we did with the theme music.

Right-click the Audio folder in your FileSystem and select New Scene… Rename it toย Sound and click OK.

Tell Godot what kind of scene this is by clicking Other Node and selecting Node.

Rename the Node to Sound (in the Scene tab). Then, attach a new script to this node!

Copy & Paste the Code into Godot

extends Node

enum Type {

# Plays a sound. The AudioStreamPlayer node will be added to the 'parent'
# specified as a parameter.
func play(type: int, parent: Node, stream: AudioStream, volume_db: float = 0.0, pitch_scale: float = 1.0) -> Node:
    var audio_stream_player: Node
    match type:
            audio_stream_player = AudioStreamPlayer.new()
            audio_stream_player = AudioStreamPlayer2D.new()

    audio_stream_player.bus = "Effects"
    audio_stream_player.stream = stream
    audio_stream_player.volume_db = volume_db
    audio_stream_player.pitch_scale = pitch_scale
    var _err = audio_stream_player.connect("finished", audio_stream_player, "queue_free")
    return audio_stream_player

The Code Explained

While the theme music will play at the same loudness and rate throughout the game, our sound effects can get louder or softer the closer/further away we are from the object creating that sound. That’s where the POSITIONAL_2D line of code comes into play as these effects are relative to the position of the player.

Finishing the Set Up

Click this icon, found in the top right of your screen, to exit out ofย  distraction free mode.

Let’s make it so these sound effects are readily playable at any point in the game. Clickย Project in the top left of your screen and selectย Project Settings…

In the AutoLoad tab, click the folder icon and select the Sound.tscn file and click Open.

You should now be able to add this by clicking Add.

Double-check that the Singleton button is checked off next to it.