TExcelTAD
Home › Godot 4 with GDScript › Mini Project: Coin Climber

Mini Project: Coin Climber

Time to put the course together in one small, complete platformer. Coin Climber has a player with coyote time, jump buffering and variable jump height, collectible coins, spikes that send you back to the start, a goal, a HUD and a level described by a text map. You build it twice:

  1. as one runnable script, so every rule of the game is checked in headless Godot right here: the run below plays the level with a recorded set of key presses;
  2. as scenes in the editor (player, coin, level, HUD), the way you would organise a real project.

What you use: CharacterBody2D & move_and_slide, Platformer Movement with Input, Areas, Collision Layers & Raycasts, Signals, UI: Controls, Containers & Themes and The Input Map & Input Events.

Step 1: tune the jump on paper

Level design follows from the jump. With a jump speed v and gravity g, the apex is v² / 2g and the time in the air is 2v / g; multiply that by the run speed for the distance. The game steps physics 60 times per second, so the real jump is a little lower than the formula:

gdscript · try it yourself
extends SceneTree
## How high and how far does Coin Climber's jump go? Formula vs. a 60 Hz simulation.

const SPEED := 120.0
const JUMP_VELOCITY := -300.0
const GRAVITY := 900.0
const TILE := 16.0

func _init():
	var v := -JUMP_VELOCITY
	var apex := v * v / (2.0 * GRAVITY)
	var air := 2.0 * v / GRAVITY
	print("formula: apex %.1f px (%.2f tiles), air time %.3f s, distance %.1f px (%.1f tiles)" % [apex, apex / TILE, air, air * SPEED, air * SPEED / TILE])

	# The same jump stepped like _physics_process: gravity first, then move.
	var dt := 1.0 / 60.0
	var y := 0.0
	var vy := JUMP_VELOCITY
	var top := 0.0
	var frames := 0
	while true:
		vy += GRAVITY * dt
		y += vy * dt
		frames += 1
		top = minf(top, y)
		if y >= 0.0:
			break
	print("60 Hz:   apex %.1f px, back down after %d frames (%.3f s), distance %.1f px" % [-top, frames, frames * dt, frames * dt * SPEED])
	quit()
formula: apex 50.0 px (3.12 tiles), air time 0.667 s, distance 80.0 px (5.0 tiles)
60 Hz:   apex 47.5 px, back down after 39 frames (0.650 s), distance 78.0 px

So with 16-pixel tiles: a ledge two tiles up is an easy jump, three is nearly impossible, and a gap of up to four tiles can be cleared. The level below uses exactly those numbers.

Step 2: the whole game in one script

Read it top to bottom; every part is something you met in the course:

  • LEVEL is a text map: # ground, C coin, ^ spikes, G goal, P player start. _ready() turns each character into a node: a StaticBody2D for ground, an Area2D for triggers. This is the same idea as a TileMapLayer, with no editor needed.
  • Player is an inner class extending CharacterBody2D. Movement happens in _physics_process: gravity, the coyote timer (jump shortly after walking off a ledge), the jump buffer (a press just before landing still counts), a short hop when the button is released early, then move_and_slide().
  • Triggers use body_entered, connected to a handler with bind(area) so one function serves every coin. Coins are removed with queue_free().
  • The level talks to the HUD through its own coins_changed and level_won signals, so the HUD knows nothing about coins or players.
  • The demo pilot at the bottom presses move_right and jump at fixed frames through Input.action_press(), exactly as if a player held the keys. It runs in _process, so each press is seen by the next physics step, just like real input that arrives between frames. Because the frame rate is fixed, the run is identical every time.
gdscript · try it yourself
extends Node2D
## Coin Climber: a one-file platformer. The level is built from the text map below.

# frames: 300
const TILE := 16
const LEVEL := [
	"..........................G.",
	"........................###.",
	"......................C.....",
	"....................###.....",
	".......C.........C..........",
	"................###.........",
	"P..C..^^....................",
	"##############..............",
]


class Player extends CharacterBody2D:
	signal jumped(kind: String)

	const SPEED := 120.0          # px/s
	const JUMP_VELOCITY := -300.0 # px/s, up is negative
	const GRAVITY := 900.0        # px/s²
	const COYOTE_TIME := 0.1      # s you may still jump after walking off a ledge
	const JUMP_BUFFER := 0.1      # s an early jump press is remembered

	var _coyote := 0.0
	var _buffer := 0.0

	func _physics_process(delta: float) -> void:
		if is_on_floor():
			_coyote = COYOTE_TIME
		else:
			_coyote -= delta
			velocity.y += GRAVITY * delta

		if Input.is_action_just_pressed("jump"):
			_buffer = JUMP_BUFFER
		else:
			_buffer -= delta

		if _buffer > 0.0 and _coyote > 0.0:
			var kind := "coyote" if not is_on_floor() else ("buffered" if _buffer < JUMP_BUFFER else "normal")
			velocity.y = JUMP_VELOCITY
			_buffer = 0.0
			_coyote = 0.0
			jumped.emit(kind)

		if Input.is_action_just_released("jump") and velocity.y < 0.0:
			velocity.y *= 0.5   # short hop when the button is let go early

		velocity.x = Input.get_axis("move_left", "move_right") * SPEED
		move_and_slide()


signal coins_changed(collected: int, total: int)
signal level_won

var player: Player
var spawn := Vector2.ZERO
var coins := 0
var total_coins := 0
var frame := 0
var hud := Label.new()


func _ready() -> void:
	for action in ["move_left", "move_right", "jump"]:
		if not InputMap.has_action(action):
			InputMap.add_action(action)   # in the editor: Project Settings > Input Map

	for row in LEVEL.size():
		var line: String = LEVEL[row]
		for col in line.length():
			var pos := Vector2(col + 0.5, row + 0.5) * TILE
			match line[col]:
				"#": _add_shape(StaticBody2D.new(), pos, Vector2(TILE, TILE))
				"C": _add_trigger("Coin", pos, _on_coin); total_coins += 1
				"^": _add_trigger("Spike", pos, _on_spike)
				"G": _add_trigger("Goal", pos, _on_goal)
				"P": spawn = pos

	player = Player.new()
	player.name = "Player"
	_add_shape(player, spawn, Vector2(12, 14))
	player.jumped.connect(func(kind: String): _log("%s jump at x=%d" % [kind, player.position.x]))

	var layer := CanvasLayer.new()   # HUD drawn on top, ignoring the camera
	layer.add_child(hud)
	add_child(layer)
	coins_changed.connect(_update_hud)
	level_won.connect(func(): _log("goal! HUD says: " + hud.text))
	_update_hud(0, total_coins)


func _physics_process(_delta: float) -> void:
	if player.position.y > LEVEL.size() * TILE + 64:   # fell off the map
		_respawn("fell off the map")


func _add_shape(body: CollisionObject2D, pos: Vector2, size: Vector2) -> void:
	var shape := CollisionShape2D.new()
	var rect := RectangleShape2D.new()
	rect.size = size
	shape.shape = rect
	body.add_child(shape)
	body.position = pos
	add_child(body)


func _add_trigger(kind: String, pos: Vector2, handler: Callable) -> void:
	var area := Area2D.new()
	area.name = kind
	area.body_entered.connect(handler.bind(area))
	_add_shape(area, pos, Vector2(10, 10))


func _on_coin(_body: Node2D, coin: Area2D) -> void:
	coins += 1
	_log("coin at x=%d" % coin.position.x)
	coin.queue_free()
	coins_changed.emit(coins, total_coins)


func _on_spike(_body: Node2D, _spike: Area2D) -> void:
	_respawn("hit spikes")


func _on_goal(_body: Node2D, _goal: Area2D) -> void:
	level_won.emit()
	get_tree().quit()


func _respawn(reason: String) -> void:
	_log("%s, back to start" % reason)
	player.position = spawn
	player.velocity = Vector2.ZERO


func _update_hud(collected: int, total: int) -> void:
	hud.text = "Coins %d/%d" % [collected, total]


func _log(text: String) -> void:
	print("frame %3d: %s" % [frame, text])


# --- Demo pilot: replays key presses at fixed frames, so this run is repeatable. ---
# In the real game, delete it and play with the keys you mapped in the Input Map.
const PILOT := {
	10: "+move_right",
	85: "+jump", 104: "-jump",
	169: "+jump", 194: "-jump",
	198: "+jump", 224: "-jump",
	234: "+jump", 259: "-jump",
}

func _process(_delta: float) -> void:
	frame += 1
	var cmd: String = PILOT.get(frame, "")
	if cmd.begins_with("+"):
		Input.action_press(cmd.substr(1))
	elif cmd.begins_with("-"):
		Input.action_release(cmd.substr(1))
frame  30: coin at x=56
frame  54: hit spikes, back to start
frame  85: normal jump at x=70
frame 114: coin at x=120
frame 169: coyote jump at x=238
frame 197: coin at x=280
frame 202: buffered jump at x=297
frame 232: coin at x=360
frame 236: buffered jump at x=365
frame 266: goal! HUD says: Coins 4/4

Read the log like a replay. The pilot walks straight into the spikes the first time (frame 54) and respawns, but the first coin stays collected. At frame 169 it presses jump after walking off the end of the ground: the coyote timer still allows it. At frames 202 and 236 it presses jump a few frames before landing on the next platform: the buffer turns that press into a jump on the landing frame. Without these two timers, both presses would be lost and the pilot would fall. Try it: set COYOTE_TIME or JUMP_BUFFER to 0.02 (about one frame) in your own copy, and the same key presses end with the pilot falling off the map.

Tip: A replay like this is a cheap regression test. Keep a few recorded runs; if a change to the movement code breaks one of them, you will see the exact frame where the new run differs.

Step 3: split it into scenes

In a real project each part is its own scene, so a designer can place coins and spikes in the editor and you reuse them in many levels. The scene tree:

text
Main (Node2D)                       main.gd: counts coins, respawns, emits coins_changed / level_won
├── Level (TileMapLayer)            ground tiles with a physics layer in the TileSet
├── Player (CharacterBody2D)        player.gd (the Player class above)
│   ├── CollisionShape2D            RectangleShape2D 12 × 14
│   ├── AnimatedSprite2D            idle / run / jump animations
│   └── Camera2D                    position smoothing on, limits set to the level
├── Coins (Node2D)
│   ├── Coin (Area2D)               instance of coin.tscn
│   └── Coin2 (Area2D)
├── Spikes (Node2D)                 instances of spike.tscn
├── Goal (Area2D)
└── HUD (CanvasLayer)
    └── CoinLabel (Label)           hud.gd

Steps in the editor:

  1. Project Settings > Input Map: add move_left, move_right and jump, and bind keys and gamepad buttons to them (see The Input Map & Input Events).
  2. Create player.tscn with the nodes above. Attach player.gd: the body of the Player class, with class_name Player and extends CharacterBody2D at the top.
  3. Create coin.tscn: an Area2D root with a CollisionShape2D and a Sprite2D. Put it in a group coins (Node dock > Groups).
  4. Build the level: a TileMapLayer with a TileSet that has a physics layer, painted with the tile tools. Drag coin and spike instances into the scene.
  5. Create the HUD: a CanvasLayer with a Label anchored to the top-left corner.
  6. Save main.tscn, set it as the main scene (Project Settings > Application > Run > Main Scene) and press F5.

The coin scene emits its own signal instead of knowing about the score, and the main scene connects to it (signals up, calls down):

gdscript
# coin.gd, on the Area2D root of coin.tscn
extends Area2D

signal collected

func _ready() -> void:
	body_entered.connect(_on_body_entered)

func _on_body_entered(body: Node2D) -> void:
	if body is Player:
		collected.emit()
		queue_free()
gdscript
# main.gd
extends Node2D

signal coins_changed(collected: int, total: int)

@onready var player: Player = $Player
@onready var hud: Label = $HUD/CoinLabel
var coins := 0
var total_coins := 0

func _ready() -> void:
	for coin in get_tree().get_nodes_in_group("coins"):
		coin.collected.connect(_on_coin_collected)
		total_coins += 1
	coins_changed.connect(func(c: int, t: int): hud.text = "Coins %d/%d" % [c, t])
	coins_changed.emit(0, total_coins)

func _on_coin_collected() -> void:
	coins += 1
	coins_changed.emit(coins, total_coins)

The player scene file that the editor writes looks like this (trimmed; the editor also adds uid values):

ini
[gd_scene format=3]

[ext_resource type="Script" path="res://player.gd" id="1_player"]

[sub_resource type="RectangleShape2D" id="RectangleShape2D_body"]
size = Vector2(12, 14)

[node name="Player" type="CharacterBody2D"]
script = ExtResource("1_player")

[node name="CollisionShape2D" type="CollisionShape2D" parent="."]
shape = SubResource("RectangleShape2D_body")

[node name="Camera2D" type="Camera2D" parent="."]
position_smoothing_enabled = true

Ideas to extend it

  • Animations: switch the AnimatedSprite2D between idle, run and jump from velocity and is_on_floor(), and flip it with flip_h when moving left (AnimationPlayer & AnimatedSprite2D).
  • Checkpoints: an Area2D that updates spawn when touched, so spikes send you back to the last checkpoint, not the start.
  • Juice: a short Tween that scales the coin up and fades it out before queue_free() (Timers & Tweens), a camera shake on death, a sound on an SFX bus (Audio & Audio Buses).
  • Saving: store the best time and the coins found per level with ConfigFile (Saving).
  • States: move the player's logic into the idle/run/jump/fall states of A State Machine in GDScript once it grows.
  • Ship it: export a Web build and upload it to itch.io (Exporting).

Test yourself

In the replay, why does the press at frame 169 still produce a jump even though the player has already walked off the ground?

  1. The pilot cheats by teleporting the player
  2. The coyote timer still allows a jump for 0.1 s after leaving the floor
  3. move_and_slide() always allows one jump in the air
  4. Gravity is off at the edge of a platform

Why does the demo pilot press keys in _process rather than inside the player's _physics_process?

  1. Input.action_press only works in _process
  2. So each press is seen by the next physics step as a fresh 'just pressed', like real input arriving between frames
  3. Because _process runs before _ready
  4. It makes the game run faster

The jump has an apex of about 48 px with 16-pixel tiles. Which ledge height is a comfortable jump?

  1. 2 tiles (32 px)
  2. 3 tiles (48 px)
  3. 4 tiles (64 px)
  4. Any height, because of the jump buffer