2D platformer
In this tutorial you make Pixel Platformer, a short but complete 2D platformer: you run and jump through a level painted with tiles, pick up coins, stomp on robots (or lose a heart if they touch you) and reach the flag at the end.
You don’t need to know much programming: every piece of code comes with comments (the lines
that start with #) that say what it does. Along the way you’ll see how Gobu is organised:
- Everything with behaviour is a prefab with its own code: the player, the coin, the enemy and the flag.
- The scene is the level: its tiles and where things are.
- The HUD is a
.uip(a UI) with its own code. - What they share (coins, hearts, whether you won) lives in an interface (
.iface.gro). - The Game Mode starts each match: it creates the player where the level says, shows the HUD and runs the rules of the game, as Unreal’s GameMode.
Every document (.scene, .prefab, .uip) carries its code inside, and that code runs on its
root actor. There are no scripts on child actors.
1. Create the project
Section titled “1. Create the project”In the project manager, press Create, give it a name and leave 2D Project on. The game’s
files go in resources/ (that is what res:// points to); Gobu finds prefabs, interfaces and
sounds by file name, so organise the folders as you like.
It is pixel art, so open Project Settings (Ctrl+Shift+,) and change:
| Setting | Value | Why |
|---|---|---|
display/window/size/viewport_width × viewport_height | 640 × 360 | The size the game is drawn at |
display/window/size/window_width_override × window_height_override | 1280 × 720 | The window, twice as big |
display/window/stretch/mode | canvas_items | Scales the 640 × 360 to the window |
rendering/textures/canvas_textures/default_texture_filter | Nearest | Sharp pixels, not blurry |
physics/2d/default_gravity | 900 | How fast everything falls (980 by default) |
2. The art and the sounds
Section titled “2. The art and the sounds”The art is Pixel Platformer and the sounds are Digital Audio, both by Kenney and in the public domain (CC0). Drag the files onto the Assets panel:
assets/art/tiles.png:Tilemap/tilemap_packed.pngfrom the pack, 18 × 18 tiles.assets/art/characters.png:Tilemap/tilemap-characters_packed.png, 24 × 24 characters.assets/art/sky.png: the first background oftilemap-backgrounds_packed.png(96 × 72).assets/sounds/:coin.ogg(powerUp2),jump.ogg(phaseJump1),stomp.ogg(pepSound1),hurt.ogg(lowDown) andwin.ogg(zapThreeToneUp).
Code uses a sound by its file name (use audio::jump), so the names matter.
3. Controls
Section titled “3. Controls”The game uses Enhanced Input (Input): the code talks about actions (move,
jump), not keys, so you can change the keys without touching it. In the input/ folder create:
move.inputaction, an action withvalue_type= Axis 1D: -1 left, 1 right.jump.inputaction, an action withvalue_type= Bool: pressed or not.controls.inputcontext, the keys for both:
| Action | Key | Modifiers |
|---|---|---|
move | D, → | none |
move | A, ← | InputModifierNegate (turns 1 into -1) |
jump | Space, W, ↑ | none |

4. The tile set
Section titled “4. The tile set”Create a TileSet resource, assets/world_tiles.resource, and open it: the TileSet panel
opens at the bottom.
- Set its Tile Size to 18 × 18.
- Drag
tiles.pngonto the Tile Sources list and answer Yes when it offers to create the tiles in the non-transparent regions. - In the inspector, add a Physics Layer. Its layer 1 is the world.
- In Paint, choose the physics layer and paint a full square on every ground tile: the grass tops and the dirt.
- The floating platforms (the thin tiles with grass) only stop you from above: paint them too and turn on One Way in their collision. You jump through them from below and land on them.

5. What the game shares: the game interface
Section titled “5. What the game shares: the game interface”The coin adds coins, the enemy takes hearts away, the flag wins, and the HUD shows all of it.
None of them needs to know about the others: they share a global interface. Create
scripts/game.iface.gro:
# What the game shares. `global`: one for the whole game, the same for# everyone who uses it.interface game global { # `live`: whoever uses it can `watch` it and react when it changes. live coins : int = 0 live hearts : int = 3 live won : bool = false # True for a moment after a hit. mut invulnerable : bool = false
# Takes a heart, unless the player still blinks from the last hit. fn hurt() void { if invulnerable or won or hearts == 0 { return } invulnerable = true # `set` tells whoever watches it (HUD, player, rules). set hearts -= 1 }}livefields can be watched withwatch: the HUD redraws itself when they change.hurt()takes a heart unless the player is still blinking from the last hit. Inside the interface the change is writtenset hearts -= 1: a plainhearts -= 1changes the value without telling anyone (Reactive state). From outside,game.coins += 1notifies on its own.
6. The player
Section titled “6. The player”Create prefabs/player.prefab with these actors:
Player(CharacterBody), the root. In Collision, layer 2 and mask 1: it is the player and it collides with the world.Sprite(Sprite) withcharacters.pngas its Texture, Hframes 9 and Vframes 3 (the sheet has 9 columns and 3 rows of characters) and Frame 0: the green alien.CollisionShapewith a RectangleShape of 14 × 18, 3 px down: the body, not the helmet.Camera(Camera) with Position Smoothing on and Limit left 0, top 0, right 2376 (the width of the level) and bottom 360.AnimationPlayer(AnimationPlayer) andAnimationTree(AnimationTree): the animations and who picks them, below.
Its animations: a state machine, without code
Section titled “Its animations: a state machine, without code”The player has three animations, and which one plays depends on what it is doing. Instead of writing that in code, you draw it as a state machine, as in Unreal’s Animation Blueprints: each animation is a state, and the arrows say when to go from one to another.
- Select
AnimationPlayerand, in the Animation panel, create three animations with a track forSprite>frame(the character drawn):idle(frame 0),walk(frame 0, and frame 1 at 0.125 s; 0.25 s long and looping) andjump(frame 1). - Select
AnimationTree: set Anim Player toAnimationPlayer, Advance Expression Base Node toPlayer(the expressions below ask it) and Tree Root to a new AnimationNodeStateMachine. - In the AnimationTree panel, add the three animations as states and join them with transitions. Give every transition Advance Mode = Auto and, except Start → idle, an Advance Expression:
| From | To | Advance Expression |
|---|---|---|
| Start | idle | (none) |
| idle | walk | is_on_floor() and velocity.x != 0 |
| walk | idle | is_on_floor() and velocity.x == 0 |
| idle, walk | jump | not is_on_floor() |
| jump | idle | is_on_floor() and velocity.x == 0 |
| jump | walk | is_on_floor() and velocity.x != 0 |
Each expression is asked of the player every frame: is_on_floor() and velocity are its own.
Press a state’s ▶ to try it in the editor. Adding a new animation later (hurt, climb) is another
state and a few arrows, not more if in the code.
Its code:
module Player
# The actors of this prefab that the code uses, each with its type.use actor::Player as player : CharacterBody2Duse actor::Sprite as sprite : Sprite2D# The keys, the data the game shares and two sounds.use input::controls as controlsuse interface::game as gameuse audio::jump as jump_snduse audio::hurt as hurt_snd
# @editable: these numbers can be changed in the inspector.@editable mut speed : float = 130.0 # pixels per second when running@editable mut jump_speed : float = 380.0 # how hard the jump pushes up
# The hearts it had last time: to notice when one is lost.mut hearts := 3
# Runs once, when the player appears in the level.fn _ready() void { controls.enable(0) # turn the keys on}
# Runs 60 times per second, at the pace of the physics.fn _physics_process(delta: float) void { # -1 with A or ←, 1 with D or →, 0 when nothing is pressed. mut dir : float = controls.move.value()
# The match is over (the flag, or no hearts left): stand still. if not playing() { dir = 0.0 } player.velocity.x = dir * speed # Gravity pulls it down a little more every step. It is the world's # (Project Settings > Physics > 2D > Default Gravity), the same for # all. player.velocity += player.get_gravity() * delta # Move, stopping against the ground and the walls. It returns # whether it hit something; we don't need that, and `_ =` says so. _ = player.move_and_slide()
# Fell below the level. if player.position.y > 420.0 { fall() } face_where_it_walks()}
# The jump key goes down: jump, but only when standing on something.on controls.jump.started() { if player.is_on_floor() and playing() { player.velocity.y = -jump_speed # on screen, up is negative Y AudioManager.play_sound(jump_snd) }}
# The jump key comes up while still going up: a shorter jump.on controls.jump.completed() { if player.velocity.y < 0.0 { player.velocity.y *= 0.5 }}
# True while the match goes on. The rules end it when the flag is# reached or no hearts are left.fn playing() bool { return GameMode.get_match_state() == GameMode.MATCH_IN_PROGRESS}
# The sprite looks where the player walks. Which animation plays (idle,# walk, jump) isn't code: the AnimationTree's state machine picks it.fn face_where_it_walks() void { if player.velocity.x != 0.0 { sprite.flip_h = player.velocity.x > 0.0 }}
# Fell off the level: lose a heart and go back to the PlayerStart.fn fall() void { game.hurt() player.velocity = Vector2.ZERO GameMode.restart_player(player)}
# Runs every time the hearts change, from an enemy or a fall.watch game.hearts(value: int) { # Fewer than before: it was hurt. if value < hearts { AudioManager.play_sound(hurt_snd) spawn blink() # blink while the game goes on } hearts = value}
# A coroutine: it pauses at each `await` while the game goes on.async fn blink() void { # `defer` runs when the coroutine ends, however it ends. defer { sprite.visible = true game.invulnerable = false # it can be hurt again }
for _i : int in range(10) { sprite.visible = not sprite.visible # show, hide, show... await sleep(0.1) # wait a tenth of a second }}use actor::Player as player : CharacterBody2Dgives you the root actor and its methods (selfis the code, not the actor). In code the classes keep their full name:CharacterBody2D,AnimatedSprite2D.- The player only moves while the match is in progress:
GameMode.get_match_state()tells when the rules have ended it (section 11). _ = player.move_and_slide():move_and_slide()returns whether it hit something. Grost warns when a value is thrown away without saying so;_ =says you don’t need it.- The code doesn’t choose animations: it only turns the sprite towards where the player walks.
- Jumping reacts to the action with
on:startedwhen the key goes down,completedwhen it comes up. Letting go early halves the upward speed, so a tap is a short hop and holding is a full jump. - Falling off the level costs a heart, and
GameMode.restart_player(player)puts it back at the level’s PlayerStart. watch game.heartsnotices a lost heart wherever it came from (an enemy or a fall) and startsblink(), a coroutine that blinks for a second (Concurrency).
7. Coins
Section titled “7. Coins”Create prefabs/coin.prefab:
Coin(Area), the root, with Collision layer none and mask 2: it only sees the player.Sprite(AnimatedSprite) with aspinanimation: tiles 151 and 152 oftiles.png(column 11 and 12, row 7), 5 FPS, autoplay.CollisionShapewith a CircleShape of radius 7.
module Coin
use actor::Coin as coin : Area2Duse interface::game as gameuse audio::coin as coin_snd
# The player touched the coin (its mask only sees the player).# "once" instead of "on": it runs only the first time, so the coin# never counts twice.once coin.body_entered(_body: Spatial2D) { game.coins += 1 # the HUD notices and shows the new number AudioManager.play_sound(coin_snd) # Remove it from the level, at the end of the frame. coin.destroy()}once coin.body_entered(...)connects the signal of the rootArea2D, asondoes, but runs only the first time a body comes in: if the player touches the coin again before it is gone, it still counts once.destroy()removes an actor from the level. It waits for the end of the frame, so it is safe in the middle of the physics (insidebody_entered).
8. The enemy
Section titled “8. The enemy”The robot walks, turns around at walls and at the edge of its platform, and dies if you land on
it. If it touches you any other way, you lose a heart. Create prefabs/enemy.prefab:
Enemy(CharacterBody), the root, layer 3 and mask 1.Sprite(AnimatedSprite):walk(characters 18 and 19, 6 FPS, autoplay) andsquashed(character 20).CollisionShape: RectangleShape of 16 × 12, 6 px down.Hitbox(Area), layer none and mask 2, with its ownCollisionShapea little bigger (18 × 14): it detects the player.Ledge(RayCast) at (-9, 6) with Target Position (0, 12): it looks for floor just ahead of its feet.
module Enemy
use actor::Enemy as enemy : CharacterBody2Duse actor::Sprite as sprite : AnimatedSprite2Duse actor::Hitbox as hitbox : Area2Duse actor::Ledge as ledge : RayCast2Duse interface::game as gameuse audio::stomp as stomp_snd
@editable mut speed : float = 40.0 # pixels per second when walking
# -1 walks to the left, 1 to the right.mut direction : float = -1.0# Stomped: flat for a moment before it disappears.mut dead := false
fn _physics_process(delta: float) void { enemy.velocity.x = direction * speed # The same gravity as the player: the world's. enemy.velocity += enemy.get_gravity() * delta _ = enemy.move_and_slide() # The ray at its feet looks for floor just ahead. ledge.force_raycast_update() # A wall ahead, or no floor ahead: turn around. no_floor : bool = enemy.is_on_floor() and not ledge.is_colliding()
if enemy.is_on_wall() or no_floor { direction = -direction # The ray moves to the new front, and the sprite looks that way. ledge.position.x = 9.0 * direction sprite.flip_h = direction > 0.0 }}
# Something touched the hitbox (its mask only sees the player).on hitbox.body_entered(body: Spatial2D) { if dead or not (body is CharacterBody2D) { return } player : CharacterBody2D = body as CharacterBody2D # Falling and above the robot: a stomp. falling : bool = player.velocity.y > 0.0 above : bool = player.global_position.y < enemy.global_position.y
if falling and above { player.velocity.y = -220.0 # the player bounces spawn squash() } else { game.hurt() # any other touch hurts the player }}
# Flat for a moment, then gone.async fn squash() void { dead = true # its hitbox ignores the player from now on # It stops walking: _physics_process isn't called any more. enemy.set_physics_process(false) sprite.play("squashed") AudioManager.play_sound(stomp_snd) await sleep(0.4) enemy.destroy() # remove it from the level}on hitbox.body_enteredworks with any actor that came in withuse actor::, not only the root.- Stomp or hit: the enemy doesn’t know about hearts or blinking: it calls
game.hurt()and the interface and the player do the rest. - After the stomp the robot stays flat for a moment.
enemy.set_physics_process(false)stops calling its_physics_process, so it doesn’t walk any more;deadkeeps its hitbox from stomping or hurting a second time. body as CharacterBody2Dturns theSpatial2Dthe signal gives into the class it really is, afterischecked it.
9. The goal flag
Section titled “9. The goal flag”Create prefabs/flag.prefab: Flag (Area, mask 2) with a Pole (Sprite with tile
131), a Cloth (AnimatedSprite with tiles 111 and 112, 4 FPS) and a CollisionShape of
12 × 36. Its code is one line that matters:
module Flag
use actor::Flag as flag : Area2Duse interface::game as game
# The player reached the flag: the level is won. The rules, the HUD and# the player react to it on their own.on flag.body_entered(_body: Spatial2D) { game.won = true}10. The HUD
Section titled “10. The HUD”Create ui/HUD.uip:
HUD(Control), the root, full screen and with Mouse Filter = Ignore.CoinIcon(TextureRect) at the top left, with an AtlasTexture oftiles.pngshowing the coin (region 198, 126, 18, 18).Coins(Label) next to it, with an outline.Heart1,Heart2,Heart3(TextureRect) at the top right, anchored to the right, with the full heart (region 72, 36, 18, 18).Message(Label) in the middle, big, with empty text.
module HUD
use actor::Coins as coins_label : Labeluse actor::Heart1 as heart1 : TextureRectuse actor::Heart2 as heart2 : TextureRectuse actor::Heart3 as heart3 : TextureRectuse actor::Message as message : Labeluse interface::game as game
# A heart you have keeps its colours; a lost one is dark.FULL :: Color = Color(1, 1, 1, 1)EMPTY :: Color = Color(0.2, 0.2, 0.3, 0.6)
# @onready watch: runs at the start and every time the coins change.@onready watch game.coins(value: int) { coins_label.text = str(value)}
@onready watch game.hearts(value: int) { # `a if condition else b`: a if the condition holds, else b. heart1.modulate = FULL if value >= 1 else EMPTY heart2.modulate = FULL if value >= 2 else EMPTY heart3.modulate = FULL if value >= 3 else EMPTY
if value == 0 { message.text = "Try again!" }}
watch game.won(value: bool) { if value { message.text = "Level complete!" }}The HUD knows nothing about coins, robots or the player: it only watches the interface.
11. The rules and the Game Mode
Section titled “11. The rules and the Game Mode”Who decides when the match is over, and what happens then? In Gobu that is the job of the Game Mode (as in Unreal): it starts a match in every level, creates the player, shows the HUD and runs the rules, a prefab with the game’s code.
Create prefabs/rules.prefab with a single Actor called Rules, and this code:
module Rules
# The rules of the match. The Game Mode creates this prefab in every# level (Project Settings > Application > Game Mode > Rules) and it# decides when the match ends and what happens then.use interface::game as gameuse audio::win as win_snd
# The flag was reached: the match ends with a win.watch game.won(value: bool) { if value { AudioManager.play_sound(win_snd) GameMode.end_match() }}
# No hearts left: the match ends and the level starts again.watch game.hearts(value: int) { if value == 0 { GameMode.end_match() spawn restart() }}
async fn restart() void { await sleep(1.5) # time to read "Try again!" game.reset() # coins, hearts and `won` back to how they started # Load the level again: the Game Mode starts a new match there. SceneManager.restart()}- A match goes through three states: waiting to start, in progress and finished. It starts
by itself when the level is ready (with Min Players players: 1);
GameMode.end_match()finishes it, and the player stops moving (section 6). game.reset()puts every field of the interface back to its starting value before the level loads again.
Now tell the Game Mode what to use. In Project Settings > Application > Game Mode:
- Player:
res://prefabs/player.prefab. - HUD:
res://ui/HUD.uip. - Rules:
res://prefabs/rules.prefab. - Start Automatically stays on: every level starts its match without code.

12. The level
Section titled “12. The level”Create scenes/level1.scene and make it the main scene (right click → Set as Main
Scene). The level is only what is in it; its code stays empty, because the Game Mode starts
the match:
Level(Spatial), the root.Sky(Parallax) with Scroll Scale (0.3, 1), Repeat Size (480, 0) and Repeat Times 7. Inside, a Sprite withsky.png, Centered off and scale 5: the sky moves slower than the level and repeats itself.Ground(TileMapLayer) withworld_tiles.resourceas its Tile Set. Select it and paint the level in the TileMap panel: ground with grass on top and dirt underneath, holes to jump over, raised steps and floating platforms. Plants, trees and the signpost are tiles without collision.Bounds(StaticBody) with two CollisionShape with a WorldBoundaryShape: one at x = 0 with normal (1, 0) and one at x = 2376 with normal (-1, 0). They keep the player inside.PlayerStart(PlayerStart) where the player begins, standing on the ground at the left. The Game Mode creates the player there, andrestart_playerbrings it back there.- Instances of the prefabs (drag them from Assets): coins above the ground and the
platforms, a few
enemy.prefabon the floor andflag.prefabat the end. Not the player: the Game Mode brings it.

13. Play
Section titled “13. Play”Press Run (F5). Run with A/D or the arrows, jump with Space, W or ↑, and hold the key to jump higher. Land on the robots to get rid of them and reach the flag.

If something doesn’t compile, the editor marks the line. The usual suspects are the types in
use actor:: (the : Type must match the real actor) and file names in use input::,
use audio:: or use interface::.
Going further
Section titled “Going further”- Menus and controls: a main menu, a pause menu and a screen where the player changes the keys, in the next tutorial (Menus and controls).
- A second level: copy
level1.scene, paint another one and, in the rules, callSceneManager.load("level2")a moment afterwon. The Game Mode starts a new match there. - Keep the record: a
@persistentinterface saves the most coins between runs (Saving the game). - More enemies: the bats (characters 24 to 26) fly; a coroutine with
loopandawait sleepmakes them go up and down (Concurrency).
| You used | Where to read more |
|---|---|
mut, fn, module, @editable, a if c else b | Expressions, Functions, Annotations |
_ = for a value you don’t need | Functions |
use actor::, use audio::, SceneManager | Importing with use |
once coin.body_entered(...), on controls.jump.started() | Signals, Input |
live, set, watch, @onready watch | Reactive state |
A global interface with a function, reset() | Interfaces |
spawn, async fn, await sleep, defer | Concurrency |
| Game Mode, rules, matches, PlayerStart | Game flow |
| AnimationTree, a state machine with expressions | AnimationTree, AnimationNodeStateMachineTransition |
| Actions, contexts, modifiers | Input |
Next: 3D arena, with enemy waves and coroutines.
Art and sounds: Kenney (CC0). Thank you, Kenney.






