Build a platformer
Walk through the code of Pixel Climber, a complete side-scrolling platformer with text-based levels, solid tiles, coyote time, jump buffering and a following camera.
On this page
What you'll learn
- Loading levels from plain text
- A character controller with gravity and solid tiles
- Coyote time, jump buffering and variable jump height
- A smooth camera that stays inside the level
Prerequisites: Game physics and collision detection.
The full game is on the Pixel Climber project page, where you can download it or play it in your browser. This tutorial explains how its pieces work.
Levels as text#
# # = ground, B = floating block, C = coin, P = player start, F = flag, ^ = spikes
LEVELS = [
[
" ",
" ",
" C C C ",
" BBBBBBB ",
" C C ",
" BBBBBBB BB F ",
" C C BBBB ",
" BBBBB C BB ",
" C BB BBB BB ",
" P BBB ^^ C C ",
"###### ######## ########## #### ##### ###########",
"###### ######## ########## #### ##### ###########",
"######^^^^^########^^^##########^^^^####^^#####^^###########",
"############################################################",
"############################################################",
],
]
Each character is one 32 × 32 tile. Text levels are easy to edit, easy to version-control and need no editor; when they outgrow that, the tilemap editor exports CSV you can load instead (see tile maps).
The Level class turns the text into lists of rectangles:
class Level:
def __init__(self, rows):
self.solids = []
self.spikes = []
self.coins = []
self.flag = None
self.start = (TILE, TILE)
self.tiles = {}
for r, row in enumerate(rows):
for c, ch in enumerate(row):
rect = pygame.Rect(c * TILE, r * TILE, TILE, TILE)
if ch in "#B":
self.solids.append(rect)
self.tiles[(c, r)] = ch
elif ch == "C":
self.coins.append(pygame.Rect(rect.x + 9, rect.y + 9, 14, 14))
elif ch == "^":
self.spikes.append(pygame.Rect(rect.x + 4, rect.y + 16, TILE - 8, TILE - 16))
elif ch == "F":
self.flag = pygame.Rect(rect.x + 10, rect.y - TILE, 12, TILE * 2)
elif ch == "P":
self.start = (rect.x, rect.y)
self.width = len(rows[0]) * TILE
self.height = len(rows) * TILE
Solid tiles become Rects for collision. Spikes get smaller hit boxes than their tiles so the game feels fair.
Tuning numbers#
FPS = 60
TILE = 32
GRAVITY = 1800
RUN_SPEED = 230
JUMP_SPEED = 680
COYOTE_TIME = 0.1 # seconds you can still jump after walking off a ledge
JUMP_BUFFER = 0.12 # seconds a jump press is remembered before landingThe jump's peak height is JUMP_SPEED² / (2 × GRAVITY) = 680² / 3600 ≈ 128 pixels, four tiles. Strong gravity with a fast take-off gives the snappy feel players expect from platformers.
The player controller#
class Player:
def __init__(self, pos):
self.rect = pygame.Rect(pos[0] + 6, pos[1] + 2, 20, 28)
self.pos = pygame.Vector2(self.rect.topleft)
self.vel = pygame.Vector2(0, 0)
self.on_ground = False
self.coyote = 0.0
self.jump_buffer = 0.0
self.facing = 1
def update(self, dt, keys, solids):
direction = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
self.vel.x = direction * RUN_SPEED
if direction:
self.facing = direction
self.vel.y = min(self.vel.y + GRAVITY * dt, 900)
self.coyote = COYOTE_TIME if self.on_ground else max(0.0, self.coyote - dt)
self.jump_buffer = max(0.0, self.jump_buffer - dt)
if self.jump_buffer > 0 and self.coyote > 0:
self.vel.y = -JUMP_SPEED
self.jump_buffer = 0
self.coyote = 0
# Releasing jump early gives a shorter hop (variable jump height).
if self.vel.y < 0 and not (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]):
self.vel.y += GRAVITY * dt
# Resolve collisions one axis at a time.
self.pos.x += self.vel.x * dt
self.rect.x = round(self.pos.x)
for s in solids:
if self.rect.colliderect(s):
if self.vel.x > 0:
self.rect.right = s.left
elif self.vel.x < 0:
self.rect.left = s.right
self.pos.x = self.rect.x
self.pos.y += self.vel.y * dt
self.rect.y = round(self.pos.y)
self.on_ground = False
for s in solids:
if self.rect.colliderect(s):
if self.vel.y > 0:
self.rect.bottom = s.top
self.on_ground = True
elif self.vel.y < 0:
self.rect.top = s.bottom
self.vel.y = 0
self.pos.y = self.rect.y
# Sub-pixel moves can leave us resting exactly on a tile without overlapping it.
if not self.on_ground and self.vel.y >= 0 and self.rect.move(0, 1).collidelist(solids) != -1:
self.on_ground = True
Three small techniques make the controls feel responsive:
- Coyote time. For 0.1 seconds after walking off a ledge you can still jump. Without it, players feel the game ignored a jump they pressed "on time".
- Jump buffering. A jump pressed up to 0.12 seconds before landing is remembered and happens on touchdown. The press is recorded in
handle_event, which setsjump_buffer. - Variable jump height. If the jump key is released while rising, extra gravity is applied, so a tap gives a short hop and a hold a full jump.
Collisions are resolved one axis at a time, the technique from collision detection: move in x, push out of walls; move in y, push out of floors and ceilings, and set on_ground when landing. The final check handles a subtle problem: when the player rests exactly on a tile, sub-pixel gravity might not move the rect at all, so the code tests one pixel below to keep on_ground true.
Rules and camera#
def update(self, dt, keys=None):
if self.state != "playing":
return
if keys is None:
keys = pygame.key.get_pressed()
self.timer += dt
p = self.player
p.update(dt, keys, self.level.solids)
p.rect.left = max(0, p.rect.left)
p.pos.x = p.rect.x
collected = [c for c in self.coins if p.rect.colliderect(c)]
for c in collected:
self.coins.remove(c)
if p.rect.collidelist(self.level.spikes) != -1 or p.rect.top > self.level.height:
self.state = "dead"
if self.level.flag and p.rect.colliderect(self.level.flag) and not self.coins:
self.state = "won"
# Camera follows the player smoothly and stays inside the level.
target = p.rect.centerx - WIDTH / 2
self.camera += (target - self.camera) * min(1.0, dt * 8)
self.camera = max(0, min(self.level.width - WIDTH, self.camera))The camera moves a fraction of the remaining distance each frame (dt * 8), which smooths out sudden movements, and is clamped so you never see past the level's edges. Everything is drawn at world position - camera, so the level itself never moves.
Ideas for your own version#
- Add a second level to
LEVELSand load it when the flag is reached. - Add moving platforms: rects that move each frame and carry the player when
on_ground. - Replace coloured rectangles with tiles drawn in the pixel art editor.
- Add a double jump that resets on landing.
- Add enemies that patrol between two points and can be defeated by jumping on them.
Common mistakes#
- Moving both axes then resolving makes players snag on tile seams and stick to walls.
- Checking
on_groundfrom last frame for jumping without coyote time makes ledge jumps unreliable. - Drawing tiles outside the screen wastes time on big levels. The game skips tiles whose rect is off-screen.