Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: A 2D Platformer

Build a complete 2D platformer in Godot 4: project structure, player with coyote time, patrolling enemy, coins, hazards, checkpoints, level scene flow and a game state manager, with a Python logic simulation.

Time to put the pieces together. In this project you build a small but complete 2D platformer: a hero who runs and jumps, coins to collect, an enemy that patrols, spikes that hurt, a checkpoint and a goal flag that loads the next level. You will reuse ideas from movement, collisions, tilemaps and the camera.

Godot cannot run on this site, so all project files here are read-only. To let you run something, the Python blocks are stand-ins: a simulation of the game's rules (scoring, damage, respawn), not of the engine. Build the real game in the Godot editor and compare.

Plan and folder layout

Text
platformer/
  project.godot
  autoload/game_state.gd
  actors/player/player.tscn, player.gd
  actors/slime/slime.tscn, slime.gd
  pickups/coin.tscn, coin.gd
  hazards/spikes.tscn
  levels/level_1.tscn, level_2.tscn
  ui/hud.tscn, hud.gd

Group files by feature (an actor and its script side by side), not by file type. Define Input Map actions move_left, move_right, jump. Name the 2D physics layers world (1), player (2), enemy (3), pickup (4), hazard (5).

flowchart TD
    GS["GameState (autoload)<br/>score, lives, checkpoint"] --- HUD["HUD (CanvasLayer)"]
    L["Level scene"] --> TM["TileMapLayer (world)"]
    L --> PL["Player"]
    L --> EN["Slime enemies"]
    L --> CO["Coins"]
    L --> SP["Spikes"]
    L --> CP["Checkpoint"]
    L --> GO["Goal flag"]
    PL -->|"collected / hurt"| GS

The level scene holds the world; one autoload keeps the state that outlives levels.

The game state autoload

An autoload (Project Settings > Globals > Autoload) is a script that Godot creates once and keeps while scenes change. It is the right home for score, lives and the respawn point, and it announces changes with signals so the HUD never polls.

GDSCRIPT
# autoload/game_state.gd
extends Node

signal score_changed(score: int)
signal lives_changed(lives: int)
signal game_over

var score := 0
var lives := 3
var checkpoint := Vector2.ZERO

func add_score(points: int) -> void:
	score += points
	score_changed.emit(score)

func lose_life() -> bool:
	lives -= 1
	lives_changed.emit(lives)
	if lives <= 0:
		game_over.emit()
		return false
	return true

func reset() -> void:
	score = 0
	lives = 3
	score_changed.emit(score)
	lives_changed.emit(lives)

The player

Reuse the movement script from the movement lesson (gravity, move_toward acceleration, coyote time and jump buffering) and add health handling and stomping:

GDSCRIPT
# actors/player/player.gd
extends CharacterBody2D

const SPEED := 200.0
const JUMP_VELOCITY := -430.0
var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")
var invulnerable := false

@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D

func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity.y += gravity * delta
	elif Input.is_action_just_pressed("jump"):
		velocity.y = JUMP_VELOCITY
	var dir := Input.get_axis("move_left", "move_right")
	velocity.x = move_toward(velocity.x, dir * SPEED, 1600.0 * delta)
	move_and_slide()
	_animate(dir)
	_check_stomp()

func _animate(dir: float) -> void:
	if dir != 0.0:
		sprite.flip_h = dir < 0.0
	if not is_on_floor():
		sprite.play("jump")
	elif absf(velocity.x) > 10.0:
		sprite.play("run")
	else:
		sprite.play("idle")

func _check_stomp() -> void:
	for i in get_slide_collision_count():
		var col := get_slide_collision(i)
		var enemy := col.get_collider() as Node
		if enemy and enemy.is_in_group("enemy") and col.get_normal().y < -0.7:
			enemy.die()
			velocity.y = JUMP_VELOCITY * 0.6        # small bounce
			GameState.add_score(50)

func hurt() -> void:
	if invulnerable:
		return
	invulnerable = true
	if GameState.lose_life():
		global_position = GameState.checkpoint
		velocity = Vector2.ZERO
	var tween := create_tween().set_loops(6)
	tween.tween_property(sprite, "modulate:a", 0.3, 0.08)
	tween.tween_property(sprite, "modulate:a", 1.0, 0.08)
	await tween.finished
	invulnerable = false

A stomp is detected from the collision normal: if the surface the player touched points mostly upward (normal.y < -0.7), the player landed on top of it. A side hit calls hurt() instead (the slime's hurtbox Area2D does that).

Patrolling enemy, coins, spikes, goal

GDSCRIPT
# actors/slime/slime.gd
extends CharacterBody2D
const SPEED := 50.0
var direction := -1.0
@onready var ledge_check: RayCast2D = $LedgeCheck   # points down in front of the slime

func _physics_process(delta: float) -> void:
	velocity.y += 980.0 * delta
	if is_on_wall() or (is_on_floor() and not ledge_check.is_colliding()):
		direction *= -1.0
		ledge_check.position.x = absf(ledge_check.position.x) * direction
	velocity.x = direction * SPEED
	move_and_slide()

func die() -> void:
	set_physics_process(false)
	$CollisionShape2D.set_deferred("disabled", true)
	var t := create_tween()
	t.tween_property(self, "scale:y", 0.0, 0.2)
	t.tween_callback(queue_free)
GDSCRIPT
# pickups/coin.gd  (Area2D, mask = player layer)
extends Area2D
func _ready() -> void:
	body_entered.connect(func(body: Node2D) -> void:
		if body.is_in_group("player"):
			GameState.add_score(10)
			queue_free())

Spikes are an Area2D whose body_entered calls body.hurt(). The checkpoint sets GameState.checkpoint = global_position. The goal flag changes scenes with get_tree().change_scene_to_file("res://levels/level_2.tscn"). Build the level with a TileMapLayer that has physics on its ground tiles, and put the Camera2D under the player with limits that match the level.

Simulate the rules (Python stand-in)

Python Stand-in (Python, not Godot): score, lives and checkpoint rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in (Python, not Godot): the stomp test from a collision normal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Polish ideas

Add a death animation and sound, screen shake on damage (see camera), a pause menu with get_tree().paused = true, a timer, moving platforms with AnimatableBody2D, double jump and a level select. Test with the keyboard and a gamepad, and export a web build to share it (exporting).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why put score and lives in an autoload?

    Autoloads persist across scene changes, so level scenes can come and go while state remains.
  2. 2. How does the player know it landed on top of an enemy?

    get_slide_collision() gives the normal; a normal with y < -0.7 means the contact surface faces up.
  3. 3. How does the slime avoid walking off ledges?

    When the ray stops colliding there is no ground ahead, so the slime turns around.
  4. 4. Why disable the slime's CollisionShape2D with set_deferred?

    set_deferred queues the change until the physics step is done.

Summary

  • Organize by feature, define input actions and named physics layers first.
  • An autoload holds persistent state and emits signals for the HUD.
  • Player, patrolling enemy, coins, spikes, checkpoints and goal are small scenes that talk through signals and groups.
  • Detect stomps with collision normals; respawn at the checkpoint.

Next: Project: A Top-Down Shooter