DEV Community

Cover image for Teach your Godot 4 deck to sound like paper, not a photocopier
Darrell Best
Darrell Best

Posted on Originally published at angelofcuriosity.itch.io

Teach your Godot 4 deck to sound like paper, not a photocopier

Play one card sound on every draw and your players will notice by the third card. Same slide, same pitch, same everything. It stops sounding like a hand of cards and starts sounding like an office photocopier that has found its calling.

This walkthrough wires the TCG & Card Game SFX Pack into a small Godot 4 table: a deck pile that shuffles, a hand you draw into, cards that lift when you hover and land with a soft place sound when you play them. Along the way we fix the photocopier with three cheap tricks: a small pool of voices, a shuffle bag so no sound plays twice in a row, and a little pitch jitter.

A Godot 4 table with a deck pile, a hand of four cards, one hovered card and one played card, plus a log of the sounds that just played

1. Drop the sounds in

Copy these two folders from the pack's ogg/ folder into your project at res://sfx/tcg/:

  • ogg/01_card_handling/
  • ogg/05_ui_and_tabletop/

Keep the folder names. Godot imports the OGG files on its own the next time the editor gets focus. The pack ships the same names as WAV too, so if you prefer WAV, change .ogg to .wav in the script below.

2. One autoload to play them all

Save this as res://sfx.gd, then add it in Project > Project Settings > Globals > Autoload with the name Sfx.

extends Node
# Autoload this as "Sfx". Card sounds from the TCG & Card Game SFX Pack.

const ROOT := "res://sfx/tcg/"
const VOICES := 8
const BANKS := {
    "hover": ["05_ui_and_tabletop/ui_tick_01", "05_ui_and_tabletop/ui_select_01",
        "05_ui_and_tabletop/ui_select_02"],
    "draw": ["01_card_handling/card_slide_01", "01_card_handling/card_slide_02",
        "01_card_handling/card_slide_03", "01_card_handling/card_slide_04",
        "01_card_handling/card_slide_05", "01_card_handling/card_slide_06",
        "01_card_handling/card_slide_07", "01_card_handling/card_slide_08"],
    "flip": ["01_card_handling/paper_turn_03", "01_card_handling/paper_turn_05",
        "01_card_handling/paper_turn_06"],
    "place": ["01_card_handling/card_place_01", "01_card_handling/card_place_02",
        "01_card_handling/card_place_03", "01_card_handling/card_place_04"],
    "shuffle": ["01_card_handling/card_shuffle_01", "01_card_handling/card_shuffle_table",
        "01_card_handling/card_shuffle_and_bridge"],
}

var _streams := {}  # bank name -> Array of AudioStream
var _bags := {}     # bank name -> indices that have not played yet
var _last := {}     # bank name -> index that played last
var _voices: Array[AudioStreamPlayer] = []

func _ready() -> void:
    if AudioServer.get_bus_index("Cards") == -1:
        AudioServer.add_bus()
        AudioServer.set_bus_name(AudioServer.bus_count - 1, "Cards")
        AudioServer.set_bus_send(AudioServer.bus_count - 1, "Master")
    for bank in BANKS:
        _streams[bank] = []
        for path in BANKS[bank]:
            _streams[bank].append(load(ROOT + path + ".ogg"))
    for i in VOICES:
        var p := AudioStreamPlayer.new()
        p.bus = "Cards"
        add_child(p)
        _voices.append(p)

func play(bank: String, volume_db := 0.0) -> AudioStreamPlayer:
    var list: Array = _streams[bank]
    var p := _free_voice()
    p.stream = list[_next_index(bank, list.size())]
    p.pitch_scale = randf_range(0.94, 1.06)
    p.volume_db = volume_db + randf_range(-1.5, 0.0)
    p.play()
    return p

func _next_index(bank: String, size: int) -> int:
    # Shuffle bag: every sound plays once before any of them repeats,
    # and a fresh bag never starts with the sound that just played.
    if _bags.get(bank, []).is_empty():
        var bag := range(size)
        bag.shuffle()
        if size > 1 and bag[0] == _last.get(bank, -1):
            bag.append(bag.pop_front())
        _bags[bank] = bag
    var i: int = _bags[bank].pop_front()
    _last[bank] = i
    return i

func _free_voice() -> AudioStreamPlayer:
    var oldest := _voices[0]
    for p in _voices:
        if not p.playing:
            return p
        if p.get_playback_position() > oldest.get_playback_position():
            oldest = p
    return oldest  # all eight are busy, so steal the one that is nearly done
Enter fullscreen mode Exit fullscreen mode

What each part is doing:

  • BANKS maps a game action to a handful of real file names from the pack. Draws use the eight card_slide takes, plays use the four card_place takes, flips use three short paper_turn takes, hovers get a quiet ui_tick_01 or ui_select click, and the shuffle bank picks between card_shuffle_01, card_shuffle_table and card_shuffle_and_bridge.
  • The voice pool is eight AudioStreamPlayer nodes made once in _ready(). Drawing five cards fires ten sounds in well under a second (a slide and a flip each), so one player would cut itself off constantly. When all eight are busy, the script reuses the one that has played the longest, so the newest sound always wins.
  • The shuffle bag is the actual photocopier repair. Each bank deals its sounds like a deck: every take plays once before any repeats, and a new bag never opens with the take that just played.
  • Pitch jitter of plus or minus 6 percent and up to 1.5 dB of volume wobble make even the same take sound like a slightly different card.
  • Everything plays on a Cards bus that the script creates if your bus layout does not have one yet, so a volume slider in your settings only has to touch one bus.

3. The card

Save this as res://card.gd. It draws itself with a StyleBoxFlat, so you can try the whole thing before you have card art.

extends Panel
# One card. Hover lifts it, flip turns it over, click plays it.

signal clicked(card)

var title := ""
var face_up := false
var in_hand := true
var rest_y := 0.0
var _label := Label.new()

func _ready() -> void:
    size = Vector2(120, 168)
    pivot_offset = size / 2
    _label.position = Vector2(10, 10)
    _label.size = Vector2(100, 148)
    _label.autowrap_mode = TextServer.AUTOWRAP_WORD
    _label.add_theme_color_override("font_color", Color("3a2a1a"))
    _label.mouse_filter = Control.MOUSE_FILTER_IGNORE
    add_child(_label)
    _paint()
    mouse_entered.connect(_hover.bind(true))
    mouse_exited.connect(_hover.bind(false))

func flip() -> void:
    face_up = not face_up
    Sfx.play("flip")
    var tw := create_tween()
    tw.tween_property(self, "scale:x", 0.0, 0.06)
    tw.tween_callback(_paint)
    tw.tween_property(self, "scale:x", 1.0, 0.06)

func _hover(on: bool) -> void:
    if not face_up or not in_hand:
        return
    if on:
        Sfx.play("hover", -6.0)
    var lift := 30.0 if on else 0.0
    create_tween().tween_property(self, "position:y", rest_y - lift, 0.08)

func _gui_input(event: InputEvent) -> void:
    var mb := event as InputEventMouseButton
    if mb and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT and in_hand and face_up:
        clicked.emit(self)

func _paint() -> void:
    var box := StyleBoxFlat.new()
    box.set_corner_radius_all(10)
    box.set_border_width_all(4)
    box.bg_color = Color("f4ead5") if face_up else Color("7a2e3a")
    box.border_color = Color("c9a25a") if face_up else Color("f4ead5")
    add_theme_stylebox_override("panel", box)
    _label.text = title if face_up else ""
Enter fullscreen mode Exit fullscreen mode

The flip squashes the card to zero width, swaps the face halfway, and stretches it back, with a paper_turn under it. Hover only makes a sound when the mouse comes in, not when it leaves, because a click on the way out is how a hand starts sounding like a keyboard.

4. The table

Save this as res://deck.gd and put it on a Node2D in your scene.

extends Node2D
# A tiny table: a deck pile, a hand, and a spot to play cards.

const CardScript := preload("res://card.gd")
const DECK_POS := Vector2(1110, 260)
const PLAY_POS := Vector2(580, 250)
const NAMES := ["Riffle Imp", "Paper Golem", "Slide Wizard", "Felt Dragon",
    "Shuffle Gremlin", "Corner Bender", "Sleeve Knight", "Top Decker"]

var hand: Array = []
var _pile: Array = []

func _ready() -> void:
    for i in 3:  # the deck pile is three face-down cards, slightly offset
        var back := CardScript.new()
        back.in_hand = false
        add_child(back)
        back.position = DECK_POS - Vector2(i * 3, i * 3)
        _pile.append(back)

func shuffle_deck() -> void:
    Sfx.play("shuffle")
    for i in _pile.size():  # wiggle the pile while the riffle plays
        var side := 1.0 if i % 2 == 0 else -1.0
        var tw := create_tween()
        tw.tween_property(_pile[i], "rotation", 0.12 * side, 0.15)
        tw.tween_property(_pile[i], "rotation", -0.12 * side, 0.15)
        tw.tween_property(_pile[i], "rotation", 0.0, 0.15)
    await get_tree().create_timer(0.45).timeout

func draw_card() -> void:
    var card := CardScript.new()
    card.title = NAMES[randi() % NAMES.size()]
    add_child(card)
    card.position = DECK_POS
    card.clicked.connect(play_card)
    hand.append(card)
    Sfx.play("draw")
    var tw := create_tween().set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT)
    tw.tween_property(card, "position", _slot(hand.size() - 1), 0.25)
    await tw.finished
    card.rest_y = card.position.y
    card.flip()

func draw_hand(count: int) -> void:
    for i in count:
        draw_card()
        await get_tree().create_timer(0.12).timeout
    await get_tree().create_timer(0.4).timeout

func play_card(card) -> void:
    hand.erase(card)
    card.in_hand = false
    var spot := PLAY_POS + Vector2(randf_range(-20, 20), randf_range(-10, 10))
    var tw := create_tween().set_trans(Tween.TRANS_BACK).set_ease(Tween.EASE_OUT)
    tw.set_parallel()
    tw.tween_property(card, "position", spot, 0.22)
    tw.tween_property(card, "rotation", randf_range(-0.12, 0.12), 0.22)
    await tw.finished
    Sfx.play("place")
    for i in hand.size():  # close the gap in the hand
        hand[i].rest_y = _slot(i).y
        create_tween().tween_property(hand[i], "position", _slot(i), 0.15)

func _slot(i: int) -> Vector2:
    return Vector2(250 + i * 135, 520)
Enter fullscreen mode Exit fullscreen mode

Then, from your game script, deal a hand:

await deck.shuffle_deck()
await deck.draw_hand(5)
Enter fullscreen mode Exit fullscreen mode

Click a card in the hand and it slides to the play spot, tilts a little, lands with a card_place, and the rest of the hand closes the gap.

5. What I checked

I ran this exact code in Godot 4.3 (Compatibility renderer) on a 1280x720 window, with a small test script that shuffled, drew five cards, clicked the first card, hovered another one, and logged every sound that started. The screenshot above is from that run. The sound list in the corner comes from the test script, not from the tutorial code.

  • All 21 streams in BANKS loaded, from the 0.043 second ui_select_01 to the 3 second card_shuffle_01.
  • Shuffle, five draws, five flips, a hover click and a place all played on the Cards bus, with playback positions moving forward 0.1 seconds after each start. Pitches in that run ranged from 0.94 to 1.06.
  • Clicking the card moved it to the table and played card_place_04. Hovering lifted the next card exactly 30 pixels.
  • Twelve draw sounds fired in a single frame left all eight voices busy with no errors and no crash.
  • 48 picks from the draw bank had zero back-to-back repeats, and every group of eight contained all eight slides.
  • A recording of the Master bus during the run had the sounds in it, so they make it all the way out of the mixer.

Tuning tips

  • The shuffle bank includes card_shuffle_01, a full three second riffle. That is the friend at game night who shuffles like he is paid by the riffle. If your shuffle animation is short, drop it from the bank or give it its own longer animation.
  • Hover sounds should be quieter than everything else. The card already plays them at -6 dB. If players sweep the mouse across the whole hand, consider a short cooldown too.
  • Twelve sounds stacked in one frame get loud. If your game does burst draws, lower the Cards bus a few dB or play the burst at a negative volume_db.
  • Want chips and dice on the same table? Add banks with 02_chips_coins_and_dice/chips_stack_01 to 06 and dice_throw_pair_01 to 29. Twenty-nine two-dice throws in one shuffle bag is a lot of throws before anyone hears a repeat.
  • An illegal play deserves a polite no. Add a bank with 05_ui_and_tabletop/ui_error_01 to 05 and play it when a card snaps back to the hand.

Tested on Godot 4.3 with the Compatibility renderer.

The sounds in this post come from the TCG & Card Game SFX Pack on itch.io, with 382 card, chip, dice, spell, impact and UI sounds in WAV and OGG: https://angelofcuriosity.itch.io/tcg-card-game-sfx

Top comments (0)