🔊 Organizing the Sound Effects | myBetabox

🔊 Organizing the Sound Effects

Keyboard Guide

Organizing the Sound Effects

So far we’ve set up the sound effect ability to auto load in every scene of our game. Now we will tell Godot to actually play these effects!

Open up the Player Scene by clicking this icon.

Then, either click the Script icon next to Player or click the Script Workspace at the top of the interface.

Stuck? Copy & Paste the Code into Godot

extends KinematicBody2D

# stats
var score = 0

# physics
var speed = 200
var jumpForce = 600
var gravity = 800

var vel = Vector2()

# components
onready var sprite = $"Sprite"
onready var ui = $"/root/Level/CanvasLayer/UI"

onready var gameOverSound = load("INSERT YOUR FILEPATH HERE")
onready var jumpSound =     load("INSERT YOUR FILEPATH HERE")
onready var coinSound =     load("INSERT YOUR FILEPATH HERE")

func enemy_hit():
    # called when we hit an enemy
    if get_tree().reload_current_scene() == OK:
        print("GAME OVER")
        Sound.play(Sound.Type.NON_POSITIONAL, self, gameOverSound)

func collect_coin(value):
    score += value
    #print("Score:", score)
    Sound.play(Sound.Type.POSITIONAL_2D, self, coinSound)

func _physics_process (delta):
    # reset horizontal velocity
    vel.x = 0

    # movement inputs
    if Input.is_action_pressed("move_left"):
        vel.x -= speed
    if Input.is_action_pressed("move_right"):
        vel.x += speed

    # applying the velocity
    vel = move_and_slide(vel, Vector2D.UP)

    # gravity
    vel.y += gravity * delta

    # jump input
    if Input.is_action_pressed("jump") and is_on_floor():
        vel.y -= jumpForce
        Sound.play(Sound.Type.POSITIONAL_2D, self, jumpSound)

    # sprite direction
    if vel.x < 0:
        sprite.flip_h = true
    elif vel.x > 0:
        sprite.flip_h = false

Use the Copy Path feature by right-clicking each of the sound effects you’ll be using (Game Over, jumping, and coin collecting) to easily insert it into your script.

Remember that we need to put quotation marks around our path to create a string.

To toggle to the Sound script area from the play() function:

  • For Mac users: hold the Command button on the keyboard and click the mouse inside the .play() parentheses at the same.
  • For Windows users: hold the Ctrl button on the keyboard and click the mouse inside the .play() parentheses at the same time.

Remember how we have two formats for sounds in relation to objects?

NON_POSITIONAL: We’ll use this format for the Game Over sound effect. It won’t matter where our player is when the game is over to play this sound!

POSITIONAL_2D: We’ll use this for the jumping and coin collecting sound effects. We only want these sounds to play when the player is doing either of these actions!