Zig Game Development
Games are one of the most fun ways to practice a systems language: you get something on screen fast, every frame has a time budget, and memory matters. Zig works well here, and the easiest way in is raylib, a small C library for games that’s famous for being simple. Thanks to Zig’s build system you don’t install raylib separately: Zig downloads its C source and compiles it with your game. This page sets up a project, opens a window, moves a square with the arrow keys, and makes it bounce.
Why raylib, and what raylib-zig adds
Section titled “Why raylib, and what raylib-zig adds”raylib handles windows, drawing, input, sound and more, with plain functions like drawRectangle and isKeyDown. It’s written in C, so Zig can call it directly. raylib-zig is a community package on top of that: it builds raylib for you, and wraps the C functions in Zig names and types (rl.isKeyDown(.right) instead of IsKeyDown(KEY_RIGHT), Zig enums for keys and colors, slices instead of raw C strings where it can).
Its README says the current bindings are tested with raylib 6.2 and Zig 0.17.0, and we built everything on this page with Zig 0.17.1.
Set up the project
Section titled “Set up the project”Start with a fresh project and add raylib-zig as a dependency:
mkdir game && cd gamezig initzig fetch --save git+https://github.com/raylib-zig/raylib-zig#develzig fetch --save downloads the package and records it, with a hash, in build.zig.zon (see Zig Packages). raylib-zig in turn depends on raylib’s own source, which Zig fetches too.
On Linux, raylib draws through X11 and OpenGL, so the system needs their development files. On Debian or Ubuntu, these are the ones our build needed:
sudo apt install libx11-dev libxrandr-dev libxinerama-dev libxi-dev libxcursor-dev libgl-devWithout them, the build stops with errors like unable to find dynamic system library "Xcursor". On Windows and macOS, raylib uses the system’s own graphics libraries and you don’t install anything extra.
Now replace build.zig with this:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const raylib_dep = b.dependency("raylib_zig", .{ .target = target, .optimize = optimize, });
const exe = b.addExecutable(.{ .name = "game", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }), }); exe.root_module.linkLibrary(raylib_dep.artifact("raylib")); exe.root_module.addImport("raylib", raylib_dep.module("raylib")); b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe); const run_step = b.step("run", "Run the game"); run_step.dependOn(&run_cmd.step);}Two lines do the raylib work: linkLibrary(raylib_dep.artifact("raylib")) links the compiled C library, and addImport("raylib", ...) lets your code write @import("raylib"). The rest is the usual shape from Zig Build System. (zig init also makes a src/root.zig and test steps; we left them out to keep the file short, so delete src/root.zig too.)
The game loop
Section titled “The game loop”Every real-time game has the same heartbeat, about 60 times a second:
- Update: read input, move things, check collisions.
- Draw: clear the screen and draw everything in its new place.
Here’s src/main.zig: a window with an orange square you move with the arrow keys.
const rl = @import("raylib");
pub fn main() void { rl.initWindow(800, 450, "Move the square"); defer rl.closeWindow(); rl.setTargetFPS(60);
var pos: rl.Vector2 = .{ .x = 380, .y = 200 }; const speed: f32 = 200; // pixels per second
while (!rl.windowShouldClose()) { // 1. Update: move with the arrow keys. const dt = rl.getFrameTime(); // seconds since the last frame if (rl.isKeyDown(.right)) pos.x += speed * dt; if (rl.isKeyDown(.left)) pos.x -= speed * dt; if (rl.isKeyDown(.down)) pos.y += speed * dt; if (rl.isKeyDown(.up)) pos.y -= speed * dt;
// 2. Draw the frame. rl.beginDrawing(); defer rl.endDrawing();
rl.clearBackground(.ray_white); rl.drawRectangleV(pos, .{ .x = 40, .y = 40 }, .orange); rl.drawText("Arrow keys move the square", 10, 10, 20, .dark_gray); }}zig build runAn 800 by 450 window opens with a light gray background, the text “Arrow keys move the square” in the top-left corner, and a 40-pixel orange square in the middle. Hold an arrow key and it glides across the window. Close the window or press Escape to quit. raylib also prints a few dozen INFO: lines to the terminal as it starts (graphics driver, OpenGL version, shaders), which is normal.
What’s going on:
initWindow/defer closeWindow(): the same setup-and-cleanup pairing you know from Zig defer.setTargetFPS(60)makes raylib wait at the end of each frame so the loop runs about 60 times a second, instead of as fast as the CPU can.windowShouldClose()turns true when the user closes the window or presses Escape.getFrameTime()is how many seconds the last frame took, about 0.0167 at 60 FPS. Multiplying the speed by it means “200 pixels per second”, whatever the frame rate. Without it, the square would move faster on a faster computer.beginDrawing/defer endDrawing()wrap the drawing for one frame. Putting thedeferright afterbeginDrawingmeans you can’t forget to end the frame, even if you add an earlycontinuelater.rl.Vector2is raylib’s 2D point (x,yasf32). UsingdrawRectangleVwith a vector means no conversions betweenf32andi32..ray_white,.orange,.dark_grayare raylib’s built-in colors, as Zig declarations onrl.Color.
Making it bounce
Section titled “Making it bounce”Moving with the keyboard is input; a bouncing square is the start of game logic. Give the square a velocity (how far it moves per second, in x and y), and flip the direction when it hits an edge. Let’s also count the bounces and draw the count:
const std = @import("std");const rl = @import("raylib");
pub fn main() void { const width = 800; const height = 450; rl.initWindow(width, height, "Bouncing square"); defer rl.closeWindow(); rl.setTargetFPS(60);
const size: f32 = 40; var pos: rl.Vector2 = .{ .x = 100, .y = 100 }; var vel: rl.Vector2 = .{ .x = 240, .y = 180 }; // pixels per second var bounces: u32 = 0;
while (!rl.windowShouldClose()) { const dt = rl.getFrameTime(); pos.x += vel.x * dt; pos.y += vel.y * dt;
// Flip direction at the edges of the window. if (pos.x < 0 or pos.x + size > width) { vel.x = -vel.x; pos.x = @max(0, @min(pos.x, width - size)); bounces += 1; } if (pos.y < 0 or pos.y + size > height) { vel.y = -vel.y; pos.y = @max(0, @min(pos.y, height - size)); bounces += 1; }
rl.beginDrawing(); defer rl.endDrawing();
rl.clearBackground(.ray_white); rl.drawRectangleV(pos, .{ .x = size, .y = size }, if (bounces % 2 == 0) .orange else .sky_blue);
var buf: [32]u8 = undefined; const label = std.mem.printSentinel(&buf, "bounces: {d}", .{bounces}, 0) catch "bounces: ?"; rl.drawText(label, 10, 10, 20, .dark_gray); }}The square flies diagonally, bounces off each wall, and switches between orange and blue on every bounce. In our screenshot after four seconds, it had bounced twice and was near the top edge, with “bounces: 2” in the corner.
Three details worth knowing:
- Pushing back inside with
@max(0, @min(...))matters. Without it, a square that went a few pixels past the edge could still be outside on the next frame, flip direction again, and get stuck jittering in the wall. It’s one of the most common first-game bugs. drawTextwants a zero-terminated string ([:0]const u8), because raylib is C.std.mem.printSentinel(&buf, fmt, args, 0)formats into a stack buffer and adds the0at the end, with no allocation per frame. Zig Sentinel-Terminated Types explains the:0.- No allocation in the loop at all. Everything lives on the stack. That’s a good habit for games: allocate when a level loads, not 60 times a second.
Where to go next
Section titled “Where to go next”- The raylib-zig examples: the repository has many examples (shapes, textures, text, audio, 3D). After cloning it,
zig build --helplists them, andzig build basic_windowruns one, as its README explains. - raylib’s cheatsheet: raylib.com/cheatsheet lists every function. The raylib-zig names are the same in camelCase (
DrawCirclebecomesrl.drawCircle). - Web builds: raylib-zig can also build your game for the browser with Emscripten (
zig build -Dtarget=wasm32-emscripten); its README walks through the extra setup. We didn’t try that here. - Other options: Mach is a game engine and graphics toolkit written in Zig itself; SDL can also be used from Zig through its C API, as in Zig Calling C.
Practice
Section titled “Practice”1. Keep the square on screen
Section titled “1. Keep the square on screen”In the arrow-key version, you can drive the square right off the window. Stop it at the edges.
Hint: after the four if (rl.isKeyDown(...)) lines, clamp each coordinate with std.math.clamp(value, min, max). The square is 40 pixels wide and the window is 800 by 450. Add const std = @import("std"); at the top.
Show solution
const std = @import("std");const rl = @import("raylib");
pub fn main() void { rl.initWindow(800, 450, "Move the square"); defer rl.closeWindow(); rl.setTargetFPS(60);
var pos: rl.Vector2 = .{ .x = 380, .y = 200 }; const speed: f32 = 200; // pixels per second
while (!rl.windowShouldClose()) { // 1. Update: move with the arrow keys. const dt = rl.getFrameTime(); // seconds since the last frame if (rl.isKeyDown(.right)) pos.x += speed * dt; if (rl.isKeyDown(.left)) pos.x -= speed * dt; if (rl.isKeyDown(.down)) pos.y += speed * dt; if (rl.isKeyDown(.up)) pos.y -= speed * dt;
// Keep the whole square inside the 800x450 window. pos.x = std.math.clamp(pos.x, 0, 800 - 40); pos.y = std.math.clamp(pos.y, 0, 450 - 40);
// 2. Draw the frame. rl.beginDrawing(); defer rl.endDrawing();
rl.clearBackground(.ray_white); rl.drawRectangleV(pos, .{ .x = 40, .y = 40 }, .orange); rl.drawText("Arrow keys move the square", 10, 10, 20, .dark_gray); }}The square now stops flat against each wall. The right limit is 800 - 40, not 800, because pos is the square’s top-left corner.
2. Speed it up with the space bar
Section titled “2. Speed it up with the space bar”In the bouncing version, make each press of the space bar multiply the velocity by 1.2.
Hint: rl.isKeyPressed(.space) is true only on the frame the key goes down, unlike isKeyDown, which stays true while it’s held. Multiply both vel.x and vel.y.
Show solution
Add this at the top of the update part of the loop:
if (rl.isKeyPressed(.space)) { vel.x *= 1.2; vel.y *= 1.2;}Each tap makes the square 20% faster in the same direction. With isKeyDown instead, holding the key for one second would multiply the speed sixty times over, and the square would fly through the walls faster than the bounce check can catch it.
- raylib is a simple C game library; raylib-zig builds it with Zig and gives it Zig names and types.
- Add it with
zig fetch --save git+https://github.com/raylib-zig/raylib-zig#devel, thenlinkLibraryandaddImportinbuild.zig. On Linux, install the X11 and OpenGL dev packages. - A game is a loop: update, then draw, about 60 times a second with
setTargetFPS(60). - Multiply movement by
getFrameTime()so speed is per second, not per frame. - Pair
beginDrawingwithdefer endDrawing(), push objects back inside when they bounce, and don’t allocate per frame.
Next up: Zig CLI Tools, what makes a command-line program pleasant to use, and how to build one in Zig.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- raylib: the C library itself, with examples and the full cheatsheet.
- raylib-zig on GitHub: the Zig bindings, setup steps, examples and web export.
- Zig Build System guide: how dependencies and C libraries fit into
build.zig. - Mach: a game engine and graphics toolkit written in Zig.