Skip to content

Guide

How each part of Ollin works, with the code to use it. New here? Start with Getting started. Every function also has documentation in its type definitions, so your editor shows it on hover.

import { audio, createGame, devtools, input, webgl2 } from '@tlapalli/ollin'
import { rapier } from '@tlapalli/ollin/rapier'
const game = await createGame({ canvas, size: 'auto', plugins: [webgl2(), input(), audio(), rapier()] })

A plugin is a function (game) => void (or async). It registers resources (the renderer, the input state, the physics world) and systems. Get a resource with its token:

const renderer = game.get(Renderer)
const input = game.get(Input)

Your own shared things work the same way, with a typed token instead of a string key:

const Score = token<{ value: number }>('Score')
game.set(Score, { value: 0 })
game.get(Score).value++

createGame options: capacity (initial entity capacity, default 16,384; the world doubles it when full) and fixedDt (seconds per fixed step, default 1/60).

The renderer takes background (the clear color, 0xRRGGBB) and pixelArt (crisp nearest filtering for every texture, atlas and font): webgl2({ background: 0x120d17, pixelArt: true }).

Instead of creating the game and loading assets in code, you can declare them once in a .ollin file, one directive per line:

game.ollin
#game(width: 1280, height: 720, background: #1b1b1b, pixelArt: true)
#texture tiles ./art/tiles.png (frame: 16x16)
#atlas hero ./art/hero.json
#sound jump ./sfx/jump.wav
#font ui (family: "monospace", size: 16)
#map level /maps/level.tmj

Add the plugin to vite.config.ts and import the file:

vite.config.ts
import { defineConfig } from 'vite'
import { ollin } from '@tlapalli/ollin/vite'
export default defineConfig({ plugins: [ollin()] })
import { assets, game } from './game.ollin'
game.world.spawn([Position, { x: 100, y: 100 }], [Sprite, assets.hero.sprite('idle 0')])
game.get(Audio).play(assets.jump)
  • The plugin turns the file into a module that creates the game (canvas, renderer, input, and audio when you declare sounds) and loads everything in parallel. game and assets are ready when the import finishes.
  • It writes game.ollin.d.ts next to the file, so assets.hero is typed (Atlas) and your editor completes it. Commit that file.
  • A missing file, an unknown directive or a wrong option stops the build with the file and line: game.ollin:6: #texture walker: file not found: ./walkr.png.
  • #game takes width, height, background (#rrggbb), renderer (webgl2 or webgpu), pixelArt (crisp filtering for every asset), devtools, canvas (a CSS selector) and capacity. #texture takes frame (16x16), margin, spacing and filter; #font the same options as loadFont; #map a z.
  • Relative paths are bundled by Vite. Paths that start with / come from public/: put Tiled maps there, because Vite cannot see the tileset images inside a map.
  • Directives only declare things; there are no variables or expressions. Game logic stays in TypeScript.
const Velocity = defineComponent({ x: f32, y: f32 })
const Health = defineComponent({ hp: u16, max: u16 }, { hp: 3, max: 3 }) // with defaults
const e = world.spawn([Position, { x: 10, y: 20 }], [Velocity, { x: 50 }], [Health])
world.add(e, Rotation, { angle: Math.PI / 4 })
world.remove(e, Velocity)
world.has(e, Health) // true
world.despawn(e)

Components store each field as a typed array indexed by entity (Position.x[e]). This is what makes Ollin fast: a system walks plain number arrays, which the browser can process quickly and hand straight to the GPU. Field types: f32, f64, i32, u8, u16, u32.

world.spawn takes [Component, values] pairs, so TypeScript catches a misspelled field.

A query is the live list of entities that have all the given components. It is cached and kept up to date as entities change, so call world.query once, outside your systems:

const moving = world.query(Position, Velocity)
game.system((dt) => {
for (const e of moving.entities) Position.x[e] += Velocity.x[e] * dt
})

Rules worth knowing:

  • Read component arrays inside systems. const { x } = Position is fine at the top of a system, but not in your scene setup or at module level. When the world outgrows its capacity, the arrays are replaced with bigger ones, and a saved copy goes stale. It then reads as empty, so the bug shows up as sprites vanishing.
  • Loop backwards when you despawn while iterating. Despawning moves the last entity of the query into the freed slot.
  • Entity ids are reused. If you keep an entity id across frames (a target, a tween), the entity may have been despawned and its id given to a new one. Save world.generation(e) and compare it later; tween does this for you.

Built-in components: Position (x, y, z), Rotation (angle, radians), Sprite, Animation and Particle.

game.system((dt) => { /* every frame */ }) // 'update' stage
game.system((dt) => { /* fixed rate */ }, 'fixed') // logic that must not depend on frame rate
const stop = game.system(fn) // returns a function that removes it

The game runs in fixed ticks, as many per frame as needed to keep a steady rate (game.fixedDt, 1/60 s by default). Each tick runs the fixed systems, then the physics stage, where physics plugins step. Then update and render run once per frame.

Put anything that must behave the same at any frame rate in fixed: forces, moving platforms, deterministic logic. Everything else goes in update.

Smooth motion. Things that move only in fixed ticks advance at 60 Hz, which looks jerky on 120 Hz screens. Give them Interpolate and the renderer draws them between their last two ticks:

world.spawn([Position], [Sprite, { w: 16, h: 16, texture }], [Interpolate])
const { x, y } = drawnPosition(game, e) // where it is drawn this frame: follow this with the camera
Interpolate.ready[e] = 0 // after teleporting, so it jumps instead of sliding there

Rapier bodies get Interpolate automatically. Don’t add it to things you move in update.

A scene is a function that sets up a level, a menu or a screen. It may be async, and it may return a cleanup function for anything outside the engine (DOM listeners, for example).

const menu: Scene = async (game) => {
// load, spawn, add systems...
game.system(() => {
if (game.get(Input).pressed.has('Space')) void game.scene(level(1))
})
}
// Scenes with parameters are functions that return a scene.
const level = (n: number): Scene => async (game) => { /* ... */ }
await game.scene(menu)

game.scene(next) despawns every entity, removes the systems, tweens and timers the current scene added, runs its cleanup, and then runs next. Plugins and their resources stay. To restart a level, call game.scene with the same scene again.

For hot reload, put scenes in their own module and add one line to your entry file. Saving the module restarts the scene in place:

import.meta.hot?.accept('./level', (m) => m && game.scene(m.level))

Loaders cache by URL, so restarting a scene does not download or upload its assets again.

world.spawn(
[Position, { x: 100, y: 100, z: 1 }],
[Sprite, { w: 32, h: 32, texture: textures.hero, frame: 0, tint: 0xffffff, alpha: 1, flipX: 0, flipY: 0 }],
)
  • The sprite is centered on Position and rotated by Rotation if the entity has it. To place it by another point, add Anchor: [Anchor, { x: 0.5, y: 1 }] puts its bottom center on Position (characters standing on the ground), { x: 0, y: 0 } its top-left corner (UI). It turns around that point, and collisions and y-sorting use the anchored box.

  • frame picks a cell of a spritesheet (see Assets), counting left to right, top to bottom.

  • tint multiplies the image by a color (0xRRGGBB). On white art you get exactly that color; on colored art it darkens. Draw things you want to recolor in white or gray.

  • alpha fades from 0 (invisible) to 1. flipX and flipY mirror the image, e.g. to face a character left. They cost nothing.

  • Without a texture, a sprite is a solid rectangle in its tint: panels behind text, health bars, screen fades.

    // A dark band behind the HUD, and a boss health bar you shrink by changing its width.
    world.spawn([Position, { x: game.width / 2, y: 20, z: HUD }], [Sprite, { w: game.width, h: 40, tint: 0x0b0a0c, alpha: 0.6 }])
    const bar = world.spawn([Position, { x: 400, y: 20, z: HUD }], [Sprite, { w: 200, h: 8, tint: 0x7a4fa0 }])
    Sprite.w[bar] = 200 * (hp / maxHp)

Animation plays frames of a spritesheet:

world.spawn([Position], [Sprite, { w: 32, h: 48, texture: textures.walker }], [Animation, { start: 0, count: 4, fps: 8 }])
Animation.fps[e] = 0 // pause
Animation.time[e] = 0 // restart from the first frame
Animation.once[e] = 1 // play once and hold the last frame

With an atlas, Aseprite tags are ready-made animations: [Animation, hero.tags.run].

Shapes. Circle draws a sprite as the ellipse that fits its box, with smooth edges (a circle when w equals h), solid or textured. spawnLine draws a line, and moveLine moves it. For anything else, draw it once on a Canvas 2D and use it as a texture:

world.spawn([Position, { x: 100, y: 100 }], [Sprite, { w: 24, h: 24, tint: 0xf2c14e }], [Circle])
const laser = spawnLine(game, 0, 0, 200, 50, { width: 2, tint: 0xb5302a })
moveLine(laser, x1, y1, x2, y2)
const star = renderer.createTexture(32, 32, (ctx) => {
ctx.fillStyle = '#fff' // white, so tint colors it
ctx.beginPath(); /* ...lineTo the points... */ ctx.fill()
})

size decides how big the game is and how it fits the page. Size the <canvas> with CSS (width: 100%; height: 100% fills the window):

createGame({ canvas, size: 'auto', plugins }) // the canvas's size on the page
createGame({ canvas, size: { width: 1280, height: 720 }, plugins }) // always 1280 x 720, scaled to fit, with bars

Either way the canvas renders at the screen’s full resolution, so it is sharp on phones and HiDPI screens, and it follows resizes and rotations. The game works in screen pixels: game.width and game.height, screen layers, clip rectangles and input.pointer all use them, so a HUD at x: 16 sits 16 pixels from the edge on every screen. To turn a point from a DOM event into screen pixels, use game.toScreen(e.clientX, e.clientY).

Without size, the game draws the canvas’s own width and height as they are and you size it yourself.

Higher Position.z draws on top. Sprites with the same z are drawn together in as few GPU calls as possible.

For top-down and isometric games, where things lower on the screen should cover things behind them, turn a z layer into a y-sorted layer:

renderer.ySort.add(1) // sprites on z = 1 draw in order of their bottom edge

Put everything that should interleave (characters, trees, walls) on that one layer.

Additive layers add their colors to what is behind them instead of covering it, for glows, fire, magic and sparks. Particles on the layer blend the same way. Black adds nothing, so draw additive art on black or with alpha:

renderer.additive.add(5) // sprites and particles on z = 5 glow

Screen layers ignore the camera and use screen pixels, for HUDs and menus that stay put while the world scrolls:

renderer.screen.add(100)
spawnText(game, font, 'score 0', { x: 16, y: 16, z: 100 })
const camera = game.get(Camera)
camera.x = 400; camera.y = 300 // world point at the center of the screen
camera.zoom = 2
const point = camera.toWorld(input.pointer.x, input.pointer.y) // screen → world

By default the camera shows world pixels 1:1 with screen pixels, with (0, 0) at the top left. To fit a fixed-size level on any screen, set camera.zoom = Math.min(game.width / W, game.height / H) and center the camera on the level, or give the game a fixed size.

Most games want it to follow the player, stay inside the level and shake on big hits:

camera.follow(player, { lerp: 0.1 }) // trail the player; 1 (the default) keeps it centered
camera.follow(player, { deadzone: { width: 80, height: 60 } }) // the player moves freely inside this box first
camera.bounds = { x: 0, y: 0, width: map.width, height: map.height }
camera.shake(8) // up to 8 px, fading over 0.3 s
camera.follow(null) // stop

The camera follows where the entity is drawn, so physics bodies stay smooth, and it stops by itself when the entity is despawned. It lives as long as the game, so a scene that sets bounds should set it again (or to null) in the scenes that follow.

const font = await renderer.loadFont({ family: 'ui-monospace, monospace', size: 32, weight: 'bold' })
const label = spawnText(game, font, 'hola, niño', { x: 10, y: 10, z: 5, size: 16, tint: 0xf3e6c9, align: 'left' })
label.set('¿listo?')
label.tint = 0xf28c28
label.alpha = 0.5
  • loadFont draws any CSS font, including web fonts loaded with @font-face, into a texture.
  • Out of the box it has ASCII, accented Latin letters, ñ, ¿, ¡ and the macron vowels of Classical Nahuatl. Add anything else with chars: '←→♥★'. A missing character draws as ? and logs a warning.
  • Each character is a sprite, so text sorts, tints and fades like any sprite. text.entities lists those sprites.
  • align: 'center' or 'right' aligns each line on x. \n starts a new line.
const textures = await renderer.loadTextures({
hero: heroUrl,
tiles: [tilesUrl, { frameWidth: 16, frameHeight: 16 }],
})
world.spawn([Position], [Sprite, { w: 16, h: 16, texture: textures.tiles, frame: 3 }])
  • You get back an object with the same keys, so a typo is a type error, not a missing image at runtime.
  • frameWidth/frameHeight turn an image into a grid of frames. margin and spacing match Tiled’s settings.
  • filter: 'nearest' keeps pixel art crisp; webgl2({ pixelArt: true }) makes it the default for every texture, atlas and font.
  • With Vite, import images (import heroUrl from './hero.png') or use new URL('./hero.png', import.meta.url).href.

Atlases are packed spritesheets, the JSON and image that Aseprite (File > Export Sprite Sheet, with JSON data) or TexturePacker (JSON hash or array) export. Frames can have any size and be trimmed:

const hero = await renderer.loadAtlas(heroJsonUrl)
world.spawn([Position], [Sprite, hero.sprite('idle 0')], [Animation, hero.tags.run])
  • hero.sprite(name) gives the texture, frame and untrimmed size of a frame by its name in the JSON; an unknown name throws.
  • hero.tags turns each Aseprite tag into Animation values (first frame, count and fps from the frame durations). Tags play forward.
  • hero.frames[name] is the frame index, for Sprite.frame.

Loading bars. withProgress waits for several loads like Promise.all and tells you each time one finishes. Each load counts once, so pass them separately for a smoother bar, and start the game first so the bar draws:

game.start()
const bar = world.spawn([Position, { x: game.width / 2, y: game.height / 2 }], [Sprite, { w: 0, h: 8, tint: 0x1f9e9a }])
const [textures, sounds, font] = await withProgress(
[renderer.loadTextures({ ... }), game.get(Audio).loadSounds({ ... }), renderer.loadFont()],
(done, total) => (Sprite.w[bar] = (300 * done) / total),
)
const input = game.get(Input)
input.keys.has('KeyA') // held (KeyboardEvent.code)
input.pressed.has('Space') // went down this frame
input.pressed.has('Pointer') // click or tap this frame
input.pressed.has('Button0') // gamepad button this frame (any pad)
input.pointer // { x, y, down } in screen pixels, the last pointer that moved
input.pointers // Map of every pressed finger: multi-touch
input.gamepads[0]?.axes[0] // left stick, -1 to 1 (standard mapping)

Read pressed in update systems; it is cleared at the end of every frame. A frame can run zero or several fixed ticks, so logic in fixed (a platformer’s jump) should not read pressed directly: note the press in an update system and let the fixed step consume it:

let jumpBuffer = 0
game.system((dt) => {
if (input.pressed.has('Space')) jumpBuffer = 0.12 // remember the press for 120 ms
jumpBuffer -= dt
})
game.system(() => {
if (jumpBuffer > 0 && grounded) (vy = -JUMP), (jumpBuffer = 0)
}, 'fixed')

The input plugin stops touches on the canvas from scrolling or zooming the page.

Gamepads use the standard mapping. buttons[0] is the bottom face button (A, cross), buttons[9] is start, and buttons[12..15] are the d-pad (up, down, left, right).

tween(game, e, Position, { x: 300, y: 100 }, { duration: 0.5, ease: ease.out, onDone: () => {} })
tween(game, e, Sprite, { alpha: 0 }, { duration: 1 }) // fade out
const cancel = tween(game, e, Sprite, { w: 64, h: 64 }, { ease: ease.outBack })
cancel()
after(game, 2, () => spawnBoss()) // once, in 2 s
const stop = every(game, 0.5, () => spawnPetal()) // repeatedly
  • Tweens animate any numeric component field from its current value. Easing curves: ease.linear, in, out, inOut and outBack (overshoots and settles).
  • A tween stops by itself when it finishes or when the entity is despawned.
  • Tweens and timers started inside a scene end with the scene.
  • For colors, blend with mixColor(from, to, t) in a system; a tween would blend the color as a plain number.
renderer.burst({ x, y, z: 2, texture: textures.spark, tint: 0xf28c28, count: 16, speed: 200, spread: Math.PI * 2, life: 0.6, gravity: 300, size: 6 })
  • Particles move, fall and fade out on the GPU. After a burst the CPU does nothing for them, so thousands cost about the same as a few.
  • They are not entities: you can’t query or collide with them.
  • They draw after the sprites of their z layer and keep flying through scene changes until they fade.
  • Use small white textures so tint gives them any color.
  • Fire them on an additive layer to make them glow.

For pickups, enemy touches and triggers, test sprite boxes directly:

overlaps(player, coin) // do their boxes touch?
overlaps(player, spike, 4) // shrink both boxes by 4 px per side: fairer hits
const enemy = hit(player, enemies.entities) // the first one touching, or -1

These ignore rotation and check one entity against a list. Boxes follow Anchor.

Clicks and taps. entityAt finds the topmost sprite under a screen point, through the camera (or on screen layers as they are), so buttons and clickable units need no math:

if (input.pressed.has('Pointer') && entityAt(game, input.pointer.x, input.pointer.y) === startButton) start()

Walls and floors made of tiles. map.moveAndCollide moves an entity and stops it against a tile layer, one axis at a time so it slides along walls, in small steps so fast falls never pass through the floor. It tells you which axes were blocked:

const hit = map.moveAndCollide(player, vx * dt, vy * dt, 'walls')
if (hit.y) { grounded = vy > 0; vy = 0 }
if (hit.x) vx = 0

It works on orthogonal maps, with the sprite’s box; a hidden layer makes a good invisible collision layer. For isometric maps or custom rules, test tiles yourself with map.tileAt (see Tiled maps). For things that must push, bounce or stack, use physics.

Terminal window
npm install @dimforge/rapier2d-simd-compat
import { BodyType, Collider, Physics, rapier, RigidBody, Shape } from '@tlapalli/ollin/rapier'
const game = await createGame({ canvas, plugins: [webgl2(), rapier({ gravity: 25, scale: 32 })] })
world.spawn(
[Position, { x: 100, y: 0 }], [Rotation], [Sprite, { w: 32, h: 32, texture }],
[RigidBody, { type: BodyType.Dynamic }],
[Collider, { shape: Shape.Box, w: 32, h: 32, friction: 0.5, restitution: 0.2 }],
)
  • Bodies are created on the next fixed tick. From then on Rapier moves dynamic bodies and writes the result back to Position and Rotation.

  • BodyType.Kinematic bodies go the other way: you move them, physics follows, and they push and carry dynamic bodies. Use them for moving platforms, doors and elevators. Move them in a fixed system, so physics sees the move in the same tick:

    const platform = world.spawn([Position, { x: 400, y: 300 }], [Sprite, { w: 96, h: 16, texture }], [RigidBody, { type: BodyType.Kinematic }], [Collider, { shape: Shape.Box, w: 96, h: 16 }])
    let clock = 0
    game.system((dt) => void (Position.x[platform] = 400 + Math.sin((clock += dt)) * 100), 'fixed')
  • Moving bodies are interpolated automatically (see Systems and stages), and camera.follow(player) follows them where they are drawn.

  • Collider sizes are in pixels. scale is pixels per meter (Rapier works best with objects of 0.1–10 m), and gravity is in m/s².

  • For everything else (impulses, velocities, raycasts, joints), use game.get(Physics): physics.body(e) is the entity’s Rapier body, physics.world is the Rapier world, and physics.rapier is the Rapier module. These are Rapier’s own objects, so they follow Rapier’s versions (marked experimental in the reference).

  • Rapier’s type definitions need "skipLibCheck": true in tsconfig.json, which the Vite templates and create-ollin already set.

Make maps in Tiled: orthogonal or isometric, CSV layer format, with embedded or .tsj tilesets. Export them as .tmj (JSON).

Load a map once, then spawn it in every scene that uses it. game.scene clears the world, so a restart spawns it again without fetching anything:

const level = await loadTilemap(game, new URL('./level.tmj', import.meta.url).href) // before the scenes
const map = level.spawn() // in the scene
map.width, map.height, map.tileWidth, map.tileHeight
map.layers.ground // tile entities of the "ground" layer
map.objects.find((o) => o.name === 'player') // { x, y, z, width, height, properties, ... }
  • Each tile is an entity with z = layer index, so later layers draw on top.
  • Hidden layers spawn Position only, which makes them handy for invisible collision.
  • In isometric maps, object positions are converted to screen pixels.
  • Tiles flipped in Tiled (horizontally or vertically) come out with Sprite.flipX/flipY set. Rotated tiles are drawn unrotated.

Tile lookups. The map knows its grid, so collision and pathfinding never need your own copy of it:

map.tileAt('walls', x, y) // the tile entity of a layer under a world point, or -1 (also for hidden layers)
map.cellAt(x, y) // { col, row } under a world point
map.cellCenter(col, row) // the world point at the middle of a cell
map.cols, map.rows // grid size in cells

On isometric maps these work on the diamond cells, so test a character’s feet (y + h / 2), not its center: tall tiles like walls and trees grow upward from their cell. A despawned tile reads as -1, so breakable walls work by despawning them.

For enemies that walk around walls, run a breadth-first search over the cells from the player’s cell and send each enemy to the neighbor cell one step closer (examples/ocelotl in the engine repo does this in about 40 lines).

const sound = game.get(Audio)
const sounds = await sound.loadSounds({ jump: jumpUrl, coin: coinUrl }) // or sound.loadSound(url) for one
sound.play(sounds.jump, { volume: 0.8, rate: 1.2 })
sound.play(sounds.coin, { pan: -0.5 }) // a bit to the left
const stopMusic = sound.playMusic(musicUrl) // streamed, loops by default
sound.volume = 0.5 // master
sound.musicVolume = 0.3 // music channel: playMusic, and play(..., { music: true })
sound.soundVolume = 1 // everything else

playMusic streams long tracks instead of decoding them whole into memory. Two channels under the master volume let a settings menu turn the music down and keep the effects.

Browsers keep audio muted until the first click, tap or key press. The plugin unlocks it then, and starts music that was waiting for it.

plugins: [webgl2(), input(), ...(import.meta.env.DEV ? [devtools({ components: { Velocity, Health } })] : [])]
  • The key left of 1 shows or hides a panel with the renderer in use, frames per second, main-thread milliseconds per frame, and the number of entities, sprites and draw calls.
  • Click a sprite to see its components live. Pass your own components by name so they show up.
  • In the browser console, ollin.game is your game.

webgl2() works in every current browser. webgpu() has the same API and draws the same output, and falls back to WebGL2 where WebGPU is missing; renderer.backend tells which one runs. Today they cost the same, so use webgl2() unless you are experimenting.

Ollin is built to keep the main thread free. At 20,000 moving sprites it spends about 3% of a 60 fps frame on a throttled CPU, against 41% for Phaser 4 and 39% for PixiJS 8 sprites (README, Performance). The shaders read each sprite’s components straight from the ECS arrays, so the CPU never repacks sprites, and batches are rebuilt only when sprites come or go or change z or texture. To keep it that way in your game:

  • Keep per-entity data in components, not in objects or Maps.
  • Create queries once, outside systems.
  • Share textures: put sprites that appear together in one spritesheet, so they draw in one call. The devtools show the number of draw calls.
  • Use the devtools’ ms per frame, not fps. A frame at 60 fps may be using 2 ms or 15 ms of its 16.6 ms budget.