/ludra:make-2d-platformer-gamesfrom ludra
Builds 2D/3D games using the Ludra engine: platformers, top-down adventures, breakout, physics games. Creates projects from templates, validates scenes, runs headless play-tests, and reviews game feel.
Ships in ludra. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Ludra is a game engine designed for agents. A game is plain JSON (scenes made of entities and components) and every step has a command whose output you can read: validate, simulate, look at a frame, run tests. Use them. Never guess whether a game works.
Working is the floor, not the goal. Before designing a game, read DESIGN.md in this skill's folder. It covers level design, fairness checks, game feel, art direction and palettes, and a checklist to finish with.
Commands below use npx @ludra/cli, which downloads the CLI from npm on first use; its command is ludra. Always write the full @ludra/cli: a bare npx ludra would fetch an unrelated package. Inside a clone of the Ludra repository itself (its root package.json is named ludra-monorepo), use npm run ludra -- <command> from the repo root instead. Ludra needs Node.js 22.18 or newer; if npx fails, tell the user and point them to https://github.com/ersingvn/ludra.
New game: npx @ludra/cli new <folder> --template <name>, then work inside that folder. Pick the template closest to the genre and reshape it:
platformer (default): side view, gravity, running and jumping.topdown: seen from above, no gravity, the hero moves in 8 directions through a maze of walls.breakout: a paddle, a bouncing ball and bricks, all game rules in scripts.For other genres, start from the nearest one: a shmup or Pong is breakout's paddle and bounce; a dungeon crawler, twin-stick or snake-like game is topdown; an auto-runner or one-button game is platformer.
Existing game: read ludra.json, the entry scene and tests/ first.
Component reference: npx @ludra/cli components (or npx @ludra/cli components <name>). It is generated from the engine, so it is always current. Trust it over memory.
Blocks: npx @ludra/cli blocks lists ready-made, tested gameplay pieces (jump pads, keys and doors, chasing and patrolling enemies, turrets, falling and moving platforms, teleporters, coins, spikes, time limits). npx @ludra/cli add <block> --at x,y copies its scripts and art into the project and places its entities, with y being the top of the surface it sits on. Prefer blocks over writing the same thing from scratch, then customize their params, art and combinations. Each block prints how to tune it.
Repeat until the game does what the user asked:
npx @ludra/cli check validates every scene. Fix every error before doing anything else. Each diagnostic gives the JSON path and a fix: line. Apply it.npx @ludra/cli play --inputs "<script>" --ascii. Read the timeline (position, velocity, grounded per sample), the events (jump, land, collect, stomp, die, win, bounce, checkpoint, gameover, goto) and the ASCII map of the final frame. --scene scenes/level-2.scene.json plays another scene. Use --watch player,lift,enemy to time moving things, --every 0.1s for finer timing and --columns 160 for wide worlds.--screenshot 1s,end (any times, or end) to play to render real frames as PNGs into screenshots/, then open them with your image-reading tool. The ASCII map shows layout; screenshots show what players see: art, animation, particles, overlaps, readability. Do this after every visual change. It needs Chrome, Edge or Chromium installed; if none is found, say so and rely on the ASCII map.tests/<name>.test.json and run npx @ludra/cli test.npx @ludra/cli solve searches the inputs for a way to win. It proves the level can be beaten and prints the route as a test to paste into tests/. It also shows how wide each jump's timing window is: "tight" (0.1 s or less) is hard for a person, so shorten the gap, widen the landing or slow the hazard, unless that is the point.npx @ludra/cli fuzz plays hundreds of random sessions and reports script crashes and softlocks (places a player gets into but never out of), each with the --inputs that reproduce it, plus a map of where players die.npx @ludra/cli review lists what makes a game feel unfinished: untested mechanics, events nothing answers, the default HUD, a flat backdrop, plain shapes. Fix every issue (✗) and consider the ideas (○). A game with review issues is not done, even if its tests pass.npx @ludra/cli dev to play it, and to mark moments while playing: 1 too hard, 2 boring, 3 confusing, 4 love this, N their own words. Every session is recorded in recordings/.npx @ludra/cli feedback lists marks, deaths, where players stopped and crashes, scene by scene, each with a command that shows it.npx @ludra/cli replay <recording> --take 2 --mark 1 draws a contact sheet around a marked moment. Look at it, then change the game there. Don't touch what was marked love this.npx @ludra/cli replay . plays the newest recording again. same means it plays out as the player saw it, changed means your edits changed this run, diverged means the same game played differently, so something in a script isn't deterministic (Math.random, Date, a module variable). Anything but same exits 1.npx @ludra/cli replay . --test turns takes into tests in tests/recordings.test.json. A take that crashed stays red until you fix the bug.npx @ludra/cli build writes build/index.html, the whole game in one file that plays from a double click or any web host, and build/<name>-web.zip to upload to itch.io as an HTML game. It plays with a keyboard, a gamepad or a touch screen (buttons for the actions the game uses appear on the first touch); in a drawUI hook, view.touch says the player has no keyboard, so write "tap", not "press R". Before shipping, fix what review's Shipping area lists: a big download, images over 4096 px, models with millions of triangles, thousands of entities alive at once.Comma-separated segments that run back to back: action[+action]:duration.
left right up down jump action, plus wait for no input.1s, 250ms, 30f (frames at 60 fps). No duration = 0.1s tap.jump triggers only on a new press. Put wait:0.1s between two jump segments.variableJump cuts it short on release.Example: "right:0.55s, right+jump:0.45s, right:0.45s, right+jump:0.45s"
{
"tests": [
{
"name": "the level can be completed",
"inputs": "right:0.55s, right+jump:0.45s, right:0.45s",
"duration": "3s",
"assert": ["score == 1", "player.grounded == true at end", "coin-1.exists == false"]
}
]
}
Assertions: <subject> <op> <value> [at <time|end>], with op one of < <= > >= == !=.
score, deaths, won, lost, lives, events.<name> (count so far: jump, land, collect, stomp, die, win, bounce, checkpoint, gameover, goto, or a custom script event), <entityId>.x|y|vx|vy|grounded|exists, <entityId>.state.<key>."scene": "scenes/level-2.scene.json".at defaults to end. The run lasts the input script plus 1s unless duration is set.Write at least one test proving the level can be completed: "won == true" and "deaths == 0". If you cannot find an input script that completes it, the level is probably impossible. Fix the level, not the test.
Build it section by section. Get past one obstacle, print the timeline to see where the player is and when, then extend the script. Moving things are deterministic, so you can compute where a lift or enemy will be. To try several timings, loop in the shell and grep the events:
for w in 0.4s 0.5s 0.6s; do npx @ludra/cli play --inputs "<prefix>, wait:$w, right+jump:0.45s" | grep -E "stomp|die|win"; done
Prefer routes with some slack: if only one exact timing works, a human will find the level frustrating. Widen the platform or slow the enemy.
When a route is long or reactive (a breakout level, an arena), write a small autopilot instead of guessing: a Node script that creates new World(scene, { scripts }) from @ludra/core, picks the input each frame from the world state (steer the paddle under the ball, walk toward the next gem), calls world.step(new Set([...])), and prints the inputs compressed into segments with frame counts ("left:24f, wait:71f"). Paste that into the test. Keep the autopilot out of the project.
The player has a platformer component and a dynamic body; gravity pulls everything down. See the building blocks and level numbers below.
"gravity": 0 on the world. The hero has topdown (speed, directions) and a dynamic body. directions is "8" (default), "4" (no diagonals), "x" or "y"."right+up:0.5s" goes diagonally. Walls are static bodies; clampToWorld (default true) keeps the hero on screen.patrol + hazard on kinematic sensors, on either axis. They can't be stomped. Make them cross the hero's path so passing them takes timing, then sweep wait: values to prove the window is wide.sprite on layer -1, sized to the world.chasechase makes an enemy that thinks: it waits (or patrols, with a patrol), spots the hero within sight px when no wall is in between, hunts it around walls, searches where it last saw it for memory seconds when it gets away, gives up and walks home. No script needed:
"chase": { "speed": 110, "sight": 220, "memory": 2 } on a dynamic body (it bumps into walls) or a kinematic one. Add hazard (and "sensor": true) to make its touch deadly.spot and giveup events. Give spot an effect with a sound (a sting, a "!"): being seen without hearing it feels broken, and review says so. Tests can assert "events.spot >= 1" or "events.spot == 0" (a stealth route), and "hunter.x" where it ended up.seeThroughWalls: true is a nose or a radar. target can be any entity id, not just the player: a guard dog that chases a thrown bone, a wolf after the sheep.world.findPath(self, to, { size }) and steers toward path[0] each frame: the same deterministic pathfinding, around every static wall.body.bounce is how much speed a dynamic body keeps when it hits a solid: 1 reflects it perfectly, 0.5 loses half each hit, 0 (default) stops it. Each hit emits a bounce event (good for a blip sound).dynamic, "bounce": 1, "gravityScale": 0. Keep its speed constant in a script and never let it travel almost horizontally.kinematic with topdown "directions": "x": player-steered kinematic bodies stop at walls, and the ball rebounds off them. Aim the ball in the paddle's touch script by where it hit.static bodies with a script that scores and destroys itself on touch. Leave the bottom of the world open and treat a lost ball as a death (world.kill(paddle)).bounce below 1 you get bouncy balls, rubber enemies and grenades.Every scene picks its physics engine with "world": { "physics": ... }:
"arcade" (the default): boxes that never rotate, resolved one axis at a time. Tight and exactly predictable, which is what precise platformers, top-down games and breakout want."rapier": a real physics engine. Choose it when physics is the game: stacking and toppling, rolling, swinging, ropes and chains, seesaws, vehicles, catapults, destruction, physics puzzles. It is deterministic too: every machine and the browser simulate the same frames, so tests stay valid.npx @ludra/cli new my-game --template physics starts from a working Rapier level: a crate pushed to climb a cliff, a rope bridge of jointed planks and a spiked pendulum, with tests for each.
Under rapier:
body.shape is box, circle (diameter = width), capsule (good for characters), polygon (the convex shape around points: wedges, rocks, ramps) or polyline (an open line through points: hills and curved ground; static or kinematic only). points are [[x, y], ...] offsets from the center; width/height stay the bounding box.transform.rotation (degrees, clockwise), friction (0 ice … 1 rubber), density (heavier pushes lighter), fixedRotation (slides but never tips), bullet (fast things don't pass through thin walls).platformer.maxSlope and slide back from steeper ones, step onto ledges up to stepHeight, push dynamic bodies (push, 0 = can't), ride moving platforms, and jump exactly as high as under arcade."joint": { ... } or a list "joint": [{ ... }, { ... }] for several):
revolute: a hinge. Doors, wheels, pendulums, seesaws. min/max limit the angle; motorSpeed with motorForce drives it (degrees per second, clockwise).prismatic: a slider along axis (degrees). Pistons, elevators. min/max limit it in px.fixed: a weld. Compound objects.rope: at most length apart. Hanging signs, grappling.spring: pulled toward length with stiffness and damping. Bumpers, soft suspension.to is another entity's id, or empty for a fixed point in the world.anchor is where the joint sits on this body (offset from its center). A hinge, slider or weld joins the other body right there: a pendulum hinged 200 px to its left is "anchor": { "x": -200, "y": 0 }.anchor to toAnchor (an offset on the other body, or from this body's start for a world point).self.applyImpulse(x, y, at?) strikes a body (velocity += impulse / mass; at a point off-center it spins). Scale by mass for a fixed kick: self.applyImpulse(self.mass * 400, 0).self.applyForce(x, y) pushes every frame (thrusters, wind).self.angularVelocity, self.rotation, self.mass.world.raycast(from, to, { ignore }) returns the first hit { entity, x, y, distance, normal }: line of sight, lasers, "is there ground ahead?".world.physics.raw is Rapier itself (RAPIER, world, body(e), collider(e), joint(e, i), toRapier/fromRapier) for anything the components don't cover. Rapier runs y-up, so convert points with the helpers. Use it in start/update/touch, never in draw hooks.Lessons that save time:
"ball.x > 400", "crate-3.rotation != 0"), not exact values. Players stand exactly on the ground, so "player.grounded == true" is reliable."crate-top.y < 400"). Tall thin stacks topple on their own.play --watch ball,crate --every 0.1s adds a rot° column; play --screenshot 1s --debug draws every collider, joint and id over the frame. Check that art matches collider shapes, and that hinges sit where you meant.g.translate(self.x, self.y); g.rotate(self.rotation * Math.PI / 180). Sprites rotate on their own."world": { "lives": 3 }. Each death costs one; the last ends the game (lost, a gameover event, the simulation stops). Leave it out for unlimited retries. Scripts read and write world.lives (an extra life) and call world.lose() (a time limit ran out).checkpoint: {}. The first touch makes it the player's respawn point (standing on its bottom edge) and fires checkpoint once. Put them before hard parts, where the player naturally stands, and light them up when reached (ctx.recent("checkpoint", 1e9); the event's data.checkpoint is its id).prefabs/<name>.prefab.json holds { "components": { ... } }. An entity uses one with "prefab": "slime" and only the components that differ: "components": { "transform": { "x": 400, "y": 487 }, "patrol": { "speed": 120 } } (merged field by field; null removes a component). Scripts spawn them: world.spawn({ prefab: "bullet", components: { transform: { x, y } } }). Use prefabs for anything placed more than once, so a change to the slime changes every slime.scenes/. A goal's "next": "scenes/level-2.scene.json" moves on after the win screen; world.goto("scenes/level-1.scene.json") moves on from anything (a title screen, a door). Score, deaths and lives carry over; R restarts the current scene, and after game over the whole run. Each scene is checked by check and tested on its own ("scene" in a test); world.exit tells draw hooks whether a win leads on.ludra dev, ludra build) progress is saved each time a scene other than the entry starts and at each checkpoint. Next visit, the entry scene shows Continue / New game; Continue starts the saved scene again with what the player had when it began (score, lives, items, flags), at the last checkpoint. Studio and recorded sessions never save.
"world": { "save": false } on a scene: never saved there, no Continue (an arcade game that always starts fresh).world.progress.save() saves what the run has right now (fires saved, so tests assert "events.saved >= 1"), world.progress.clear() (fires cleared), world.progress.exists, and world.progress.continue() (goes to the saved game, for a title that offers it in its own way).drawMenu(ctx) hook draws both menus instead, in the game's own look, from ctx.menu (title, items, selected); the engine still handles keys, pad and taps (taps hit the default layout: centred rows 300 × 50 px).Adventures, RPGs and anything with a story, without a script. Run npx @ludra/cli components dialogue for every field.
"item": { "name": "key" } on a sensor body. A player touching it takes it into world.items (no score) and fires pickup. "count": 30 for a pile of gold. Items and flags carry over to the next scene like score."lock": { "needs": "key" } on a solid. A player carrying the key opens it (the entity is removed, the key used up unless "take": false) and unlock fires; without one, locked fires once per touch: give it a sound and a "locked" flash so the player knows why. A goal can wait for items too: "goal": { "requires": { "gem": 3 } }. check warns when something needs an item no entity or dialogue gives (W_ITEM_NOWHERE)."dialogue": { "lines": [ ... ] }. The player presses action within range (default 48 px gap) to talk; action or jump goes on, up/down pick a choice, and the player stands still meanwhile.
"dialogue": [
{ "when": { "quest": "done" }, "lines": [{ "speaker": "Smith", "text": "The bridge stands again." }] },
{ "has": { "hammer": 1 }, "lines": [{ "speaker": "Smith", "text": "My hammer!", "take": { "hammer": 1 }, "set": { "quest": "done" }, "give": { "key": 1 } }] },
{ "lines": [
{ "speaker": "Smith", "text": "The bridge is out." },
{ "text": "Will you fetch my hammer?", "choices": [
{ "text": "Yes", "set": { "quest": "hammer" }, "next": "thanks" },
{ "text": "No", "end": true } ] },
{ "id": "thanks", "text": "Thank you! It's in the old mine." } ] }
]
A list of dialogues uses the first whose when (flags) and has (items) hold, so put the later story first. A line's set/give/take happen when it is shown, a choice's when picked; a choice with when/has shows only when they hold (a shop: { "text": "Sword", "has": { "gold": 30 }, "take": { "gold": 30 }, "give": { "sword": 1 } }). next is a line index or a line's id; without next or end it goes to the line after.world.flags is the story so far, name → number, string or true/false. Dialogue set writes them; scripts read and write them (world.flags.metSmith = true) and use world.items.get/add/take/all()."right:0.4s, action:2f, wait:0.2s, action:2f, down:2f, action:2f"), then assert "flags.quest == \"hammer\"", "items.key >= 1", "events.unlock == 1", "events.talk >= 1". A test for a later scene starts with what the player brings: "carry": { "items": { "key": 1 }, "flags": { "quest": "done" } }. ludra play prints every line said and choice made. review flags a dialogue no test talks to, and silent talk and pickup events.drawUI, draw it yourself from world.talking ({ entity, line, choice, text, speaker, choices }, undefined when nobody talks): portraits, a typewriter reveal (ctx.recent("say") gives the time the line appeared), the game's font."tilemap": { "tileSize": 40, "rows": ["#....c...#", "##########"], "legend": { ... } } on an entity whose transform is the map's top-left corner.
{ "image": "assets/stone.svg" } (solid by default), with "sensor": true and "components": { "hazard": {} } for spikes, "solid": false for decoration. Or a prefab name: "c": "coin" places a coin centered in each c cell. " " and "." are empty.<id>-<row>-<col>: tests, play --watch and scripts can use them."solid": false, a foreground) are fine."cameraZone": { "width", "height", "mode", "zoom", "blend", "priority" } on an entity (no body).
"room" keeps the view inside the area (rooms, floors, an arena), "fixed" holds the view on its center (a boss fight, a vista), and zoom changes the zoom (0.5 shows twice as much).blend seconds; overlapping zones go by priority. Zones are presentation only and show in --debug screenshots as violet frames."tween": { "property": "y", "by": -120, "duration": 1, "ease": "quadOut", "repeat": "once", "delay": 0, "on": "" }, or a list.
x, y, rotation, and scale/opacity (needs a sprite). to is a fixed target, by is relative.linear, sineInOut (glide), quadIn, quadOut, quadInOut, cubicInOut, backOut (snap with overshoot), elasticOut, bounceOut. repeat: once, loop, pingpong; delay waits before every pass, so a pingpong lift rests at each end.on starts it when an event fires ("checkpoint", or a name a script emits). Scripts call self.tween({ property: "y", by: -120, duration: 0.6, ease: "quadOut" })."gate.y == 200"). Tweened kinematic bodies move by velocity and carry riders; give moving solids a kinematic body.See examples/clockwork-keep for all three together, with a test for each moving part.
npx @ludra/cli new my-game --template 3d starts from Sky Islands, a complete 3D platformer with tests. Everything above still applies (components, events, effects, sounds, tests, review); this is what changes.
"world": { "dimensions": 3 }: metres, +x right, +y up, +z toward the camera, gravity 9.81 m/s². It always runs on Rapier 3D (deterministic on every machine). Players falling below world.fallLimit (default -50) die.{ "x", "y", "z", "rotation": { "x", "y", "z" } }, degrees applied y (turn), then x (tilt), then z (roll). A single-number rotation is 2D and an error in 3D.width, height and depth (0 = width). Shapes: box, sphere (diameter = width), capsule and cylinder (upright), convex (points: [[x, y, z], ...], or a model) and mesh (exact triangles, see below). Joints work in 3D too: revolute turns around axis ({ "y": 1 } for a door; default { "z": 1 }), plus spherical ball joints; anchors take z."character": {} on a dynamic capsule (width 0.6, height 1.8).
faceMovement).maxSlope and steps up to stepHeight, pushes bodies and rides kinematic platforms."mesh": shape "auto" takes the body's shape, or box, sphere, capsule, cylinder, cone, plane, torus. Then color, roughness, metalness, emissive for what glows, opacity, a texture that tiles every textureScale metres, flatShading. A mesh without a body is scenery."light": a directional sun with shadows (shadowSize metres around the camera's focus), hemisphere sky fill, point and spot lights, ambient."camera3d": follow (behind and above the player, never turning with it, smoothed), orbit, firstPerson or fixed with lookAt."environment": sky (a color or [top, horizon]), fog, toneMapping, exposure, shadows.camera and cameraZone are 2D only (check warns), and effects' particles aren't drawn in 3D: sounds still play, and a render hook can make 3D particles.render(ctx) hook gets the real three.js every frame:
ctx.THREE (every class: InstancedMesh, ShaderMaterial, Points...), ctx.scene, ctx.camera, ctx.renderer.ctx.object, a group that moves and turns with the entity: add children in its local space.ctx.local.await ctx.addon("postprocessing/UnrealBloomPass.js") loads any three.js addon. ctx.setRender(() => composer.render()) draws the frame yourself (bloom, depth of field, outlines).ludra check runs it against stand-ins (E_RENDER_HOOK).hero.ts (a face and scarf on the capsule), clouds.ts (an instanced cloud sea), beacon.ts and portal.ts show how.self.z, self.vz, self.rotationX/rotationY, and self.spin (degrees per second around each axis).self.applyImpulse({ x, y, z }, at?) and self.applyForce({ x, y, z }, at?).world.raycast({ x, y, z }, { x, y, z }), and world.physics.raw (Rapier 3D)."chase": { "sight": 10, "speed": 3.5 } (metres, m/s) walks the ground around whatever blocks it and turns to face where it goes. A deadly one is a kinematic sensor capsule with chase and hazard: it glides at its height and kills on touch. A dynamic one (not a sensor) is pushed around and pushes back, and stays upright. world.findPath(self, to, { size, height }) gives the same ground paths to scripts (companions, units, fleeing).other.applyImpulse({ y: 12 * other.mass }) launches at 12 m/s.z, rotationX and rotationY.play --watch adds z and vz columns; assertions can use .z, .vz, .rotationX, .rotationY. Positions are floats: assert ranges ("player.z < -7.5"), not exact values. Find timings by sweeping, as in 2D.R_DEFAULT_LIGHTING), a sky (R_DEFAULT_SKY) and chosen materials (R_DEFAULT_MATERIALS), and points out solid bodies with no mesh..glb or .gltf works, skinned and animated ones included:
assets/.ludra inspect assets/knight.glb gives its size in metres, its triangles, its bones and every animation clip with its duration, and prints a "mesh" line to start from. Never guess clip names."mesh": { "model": "assets/knight.glb", "turn": { "y": 180 }, "animations": { "idle": "Idle", "walk": "Walk", "run": "Run", "jump": "Jump", "fall": "Fall" } }. It keeps its own materials, so color and texture are ignored."turn": { "y": 180 }, then check in a screenshot that they walk face first.fit "height" (the default) scales it evenly to the mesh's (or body's) height, centres it and stands its lowest point on the bottom of the body. "box" stretches it to width, height and depth, and "none" keeps its own metres. Then scale and offset (metres) adjust it.animations clip is picked from how it moves: walk under 60% of character.speed, run above, jump while rising (plays once and holds), fall coming down, idle otherwise. Leave any out. animation plays one clip forever (a windmill). A script's self.state.animation = "Wave" overrides both. fade blends between clips and animationSpeed scales them. Poses depend only on simulation time, so screenshots match live play.ctx.model is { root, clips, mixer }: find bones and materials in root, or attach a sword to a hand bone.ludra check names clips the model doesn't have (with the real list), and broken files, missing .bins and extensions the renderer can't load. Then play --screenshot to see its size, facing and pose."shape": "mesh" collides with exact triangles: points [[x, y, z], ...] plus triangles [[a, b, c], ...] indexing them. It is static or kinematic only (a dynamic one is E_MESH_DYNAMIC), for terrain, caves and level geometry."body": { "shape": "mesh", "model": "" } uses the entity's own mesh.model ("convex" takes the hull around it, for dynamic props). The CLI reads the geometry when it loads the scene and fits it exactly like the mesh, so tests and the browser use identical numbers. Point model at a simpler file to collide with fewer triangles than you draw.world.spawn with inline components: spawn a prefab instead.hazard. Touching it kills the player, who respawns at its start position. Collected items stay collected.patrol + hazard. Add "stompable": true so landing on it from above destroys it and bounces the player.patrol. It carries players standing on it. patrol runs from the start position to distance px along +x (or +y) and back.goal. Use requireScore to make collecting things mandatory. ludra check errors if the scene cannot offer enough points."width": 1920) and the camera scrolls with the player.When no built-in component does what the user wants (an enemy that chases, a door that needs a key, a timer, shooting, a boss with phases, a switch, a jump pad), write a script. Prefer built-ins when they fit; they are already tested.
Run npx @ludra/cli components script for the full API. It is generated from the engine.
Write scripts/<name>.ts:
import type { Script } from "@ludra/core";
/** Runs toward the player once they come within params.range px. */
export default {
update({ self, world, params }) {
const player = world.player();
const distance = player ? player.x - self.x : Infinity;
self.state.chasing = Math.abs(distance) < (params.range as number);
self.vx = self.state.chasing ? Math.sign(distance) * (params.speed as number) : 0;
},
} satisfies Script;
Attach it: "script": { "src": "scripts/chase.ts", "params": { "speed": 70, "range": 220 } }. Give scripted movers a body (kinematic for things that move on their own).
Run check: it loads every script and reports syntax errors with the line and a caret, forbidden imports, and misspelled hooks.
Prove the behavior in tests. Scripts expose what they do through self.state and world.emit:
"chaser.state.chasing == true", "boss.state.phase == \"angry\"""events.door-open == 1" for world.emit("door-open")won, deaths, <id>.exists, positions.Rules:
import type is allowed. Put helpers in the same file.world.random() (seeded) instead of Math.random(), and world.time instead of Date, so tests stay deterministic.self.state (or another entity's state, e.g. player.state.hasKey), not in module variables: module variables are shared by every entity using the script and survive restarts.touch fires once when touching starts, including solids that only touch. For "while touching", use self.touches(other) in update.effects too: "effects": { "door-open": { "sound": "explosion", "shake": 6 } }.scripts/ load even if nothing uses them, so world.spawn({ components: { ..., script: { src: "scripts/bullet.ts" } } }) works.See examples/key-quest in the Ludra repo for a jump pad, a key, a locked door, a chasing enemy and a time limit, all with tests.
y = surfaceTop - height / 2.jumpSpeed² / (2 · gravity). Defaults 680 and 1800 give about 128px, so keep platform rises at or below about 100px.speed · 2 · jumpSpeed / gravity (about 180px with the defaults)."sensor": true. Platformers need a "dynamic" body. Patrols need a "kinematic" body.Get the level playable with colored shapes first, then dress it. Images, effects and emitters are presentation only: they never change the simulation, so tests that passed keep passing.
You can't draw with a mouse, but you can write SVG. Put files in assets/ and point sprite.image at them.
frameWidth x frameHeight (width/height on the <svg> must match the sheet). Draw characters facing right; flip mirrors them when moving left.idle, run, jump, fall to frame lists ("0", "1-2", "0,2-4") and fps. Platformers switch automatically. Other entities play run while moving and idle otherwise, so a spinning coin is "idle": "0-3"."tile": true repeats the image at its natural size to fill the sprite. Use it for ground, platforms and spikes instead of stretching.color set even with an image: it is the fallback if the image fails to load.ludra check fails with E_ASSET_MISSING (and lists what does exist) if a referenced file is missing, so run it after adding art. Then take screenshots and look at them: check that sprites face the right way, sit on the ground instead of floating or sinking, tiles line up, and the player stands out from the background.
Scene-level effects map events (jump, land, collect, stomp, die, win) to a particle burst at the event position, a sound and a screen shake:
"effects": {
"collect": { "sound": "coin", "particles": { "count": 14, "color": "#ffd166", "speed": 140, "life": 0.45 } },
"die": { "sound": "explosion", "shake": 10, "particles": { "count": 30, "color": "#ff5d73", "speed": 220 } }
}
sound names one of the scene's own sounds (see "Sound and music" below), a preset (jump, coin, hit, explosion, powerup, blip, thud) or an audio file (.wav, .mp3, .ogg). Presets are placeholders: the same beeps in every Ludra game.direction is degrees (-90 = up, 90 = down), spread is the cone width, and negative gravity floats up.emitter component streams particles continuously (sparkles on a goal, torch fire, steam).Run npx @ludra/cli components effects for every field.
A game sounds like its world. Design its own sounds and write its music; ludra review flags stock presets and a game without music.
"sounds" (scene level): named sounds synthesized from layers, used in effects and ctx.play like presets.
wave (sine, square, sawtooth, triangle), from/to Hz, start, duration, volume, attack. A noise layer is filtered noise: filter (lowpass, highpass, bandpass), from/to filter Hz, the same timing fields.vary (0..1) changes the pitch on every play, so footsteps and hits never sound copied."music" (scene level): an audio file, or tracks of notes that loop.
tempo (BPM), steps (tokens per beat), and tracks: wave (or "noise" for drums), notes, volume, decay, filter, attack."C4 E4 G4 ~ | A3 - C4+E4 ~": a note, a chord with +, - rest, ~ hold, | bar lines for reading. Noise tracks use x/X; a low filter (≤ 250) is a kick, a high one (≥ 3000) a hat.sound(ctx) in a script gets the real Web Audio API, every rendered frame in the browser: ctx.audio (the AudioContext), ctx.out (connect here), ctx.events (events since the last call), ctx.play(name, { volume, pitch }), ctx.local for your nodes. Use it for sound that follows the game: an engine that rises with speed, wind that grows with height, a scrape while a crate slides, adaptive music layers. Like draw hooks it is read-only, and ludra check runs it against a stand-in AudioContext (E_SOUND_HOOK). Create nodes with ctx.audio.createX(), not new XNode().Run npx @ludra/cli components sounds for every field and an example of each. The physics template's scripts/ambience.ts is a full sound hook.
Use a coherent palette: a dark background, mid-tone platforms, a bright player and pickups, and a warning color (red, magenta) for anything that kills. Use layer so the player draws above everything. Keep sizes consistent, for example a 28x36 player, 20px pickups and 20px-thick platforms.
Sprites and effects are the floor. For real art, paint with code; read "Paint with code" in DESIGN.md for what to do with it.
draw(ctx) in any script paints that entity every rendered frame, in world coordinates, after its sprite (or instead of one).
ctx.g is the real CanvasRenderingContext2D: gradients, shadowBlur glow, globalCompositeOperation = "lighter" for light, paths, roundRect, text, filter, drawImage. Anything the canvas can do.sprite.layer (0 without a sprite), then entity order. A backdrop is an entity with only a draw hook, first in the list.drawUI(ctx) paints in screen space above the world. If any script has it, the default HUD and "Level complete" screen disappear and the game draws its own: score, meters, title card, win screen (world.won, world.deaths, world.score).ctx:
time (animate with it), local (per-entity memory for trails and tweens), view (size and camera), recent(name?, seconds) (events to flash or pop text on; custom event data included).image(path) (may be undefined, so check it), burst(x, y, particles), shake(px), random().self and world are read-only there: setting x, score, state, or calling emit, spawn or world.random throws, so the browser can never drift from what tests verified. Do game logic in update/touch, and world.emit("name", data) there for the visuals to react to."fonts": { "Orbitron": "google" } in the scene (or a .woff2 in assets/), then g.font = "900 32px Orbitron, sans-serif"."postfx": { "shader": "shaders/x.frag", "uniforms": { "bloom": 1.5 } }.
u_image, u_resolution, u_time, v_uv and each uniform as a float; write void main() and set gl_FragColor.play --screenshot with the line number.ludra check runs every draw hook against a mock canvas, so typos and accidental game changes show up as E_DRAW_HOOK before the browser. Then look at real frames with play --screenshot: that is the only way to judge how it looks.See scripts/ and shaders/ in the breakout (everything drawn in code) and topdown (lighting over SVG sprites) templates, and physics (a chain drawn from a pendulum's pivot).
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub ersingvn/ludra --plugin ludraOther plugins' skills for the same job