# twoDKit: 2D pixel-art platformer kit
Make side-scrolling pixel platformers in the spirit of **Celeste** and **Hollow Knight** in any Zero world. Type a level as rows of characters and get a proper tiled level with the right edge and corner tile in every cell; drop in a player who runs, jumps higher the longer you hold the button, forgives late ledge jumps and early presses, wall slides, wall jumps and dashes in eight directions, on keyboard, gamepad and phone; watch it all through a pixel-perfect camera that holds still while you jump and eases at ledges, with parallax backgrounds scrolling behind. Every style switches with one field: **14 themes (each a tile set and a four-layer parallax background), 12 characters, 11 movement feels, 3 camera styles, 8 HUD looks, 6 gem looks and 5 checkpoint looks**, and one `theme` sets the tile set and background together. Levels can hold spikes, saw blades, lava, crumbling blocks and fire jets, and hearts, dash crystals and springs, each typed as one character. Landings kick up dust and squash, dashes leave after-images, checkpoints light up with a glow and embers, and the goal plays a slow-motion win with fireworks. It is multiplayer by default: every player sees the same level and every other player running, jumping, wall jumping and dashing with the right animation.
It builds on published kits it installs with it: **controlsKit** (keyboard, gamepad and touch controls), **Trapline** (checkpoints, lives, respawn), **platformsKit** (moving platforms and lifts), and four small packages that came out of this kit and work on their own: **pixelSprites** (animated sprites), **pixelParallax** (parallax backgrounds), **pixelPaint** (paint pixel art in code) and **chipSfx** (8-bit sound effects).

## Install
Search ZeroMind for "twoDKit" or "2D platformer kit", or install it in one step (it brings controlsKit, Trapline, platformsKit, pixelSprites and pixelParallax, and what they use):
```lua
tools.use("zeromind", "installAsset", "2cfaadfa-6235-41c4-a20d-d81508632c78") -- from Luau
```
or `zero zeromind installAsset 2cfaadfa-6235-41c4-a20d-d81508632c78` in the engine shell. It lands at `/source/twoDKit.package`. Installs with several dependencies take a minute (engine issue #21420; a fresh install took 25 to 40 s in testing); while files arrive the editor may say a component "is waiting for content it requires"; that is install order and clears by itself.
### Which version did I get?
- **The kit:** `require("twoDKit.api").VERSION` in a script, or the `version:` line of `/source/twoDKit.package/package.yaml`. This README is for **1.3.0**.
- **Everything the install brought:** `zero zeromind installs` in the engine shell lists every installed package with the build it holds; each one's `package.yaml` names its version.
- **What arrives with 1.3.0** (the same as 1.2.2): Trapline 1.5.4, held to exactly that build because the kit's own files name it, with the kits Trapline is built on (SecondWind 1.4.4, Lifeline 1.0.1, MatchFlow 1.3.1, juiceKit 1.2.8, barsKit 1.4.3); and the four packages that came out of this kit and live in its own world, pixelSprites, pixelParallax, pixelPaint and chipSfx, each at its newest release (1.0.3, 1.0.3, 1.0.1 and 1.0.1 in a fresh install on the day of release).
- **Not held to a build:** controlsKit and platformsKit arrive at their newest published release (engine issue #19270), so a new install can hold a newer one than this kit was tested with (controlsKit 1.2.3; platformsKit 1.5.5 here and 1.5.7 / 1.5.8 in fresh installs). If something looks off after one of them updates, run `zero tests run twoDKitTests`.
## Make your first level in five minutes
1. **Install** (about a minute): `zero zeromind installAsset 2cfaadfa-6235-41c4-a20d-d81508632c78` in the engine shell.
2. **Three calls** (one minute): open `scenes/main.scene/build.luau`, replace the whole file with this, and press **Play**:
```lua
local PP = require("twoDKit.api")
function content()
PP.level()
PP.player()
PP.hud()
end
```
With no options you get the built-in starter level (`PP.STARTER`): grassland tiles and sky, a knight with the `tight` feel, a pixel-perfect camera, the pixel HUD, a checkpoint, spikes, a moving platform, a wall to climb and the goal. Run with A / D, jump with Space (hold it to jump higher), dash with Shift, and press E for the STYLES panel.
3. **Restyle it** (one minute): `PP.level({ theme = "candy" })`, `PP.player({ character = "slime", feel = "bouncy" })`, `PP.hud({ style = "comic" })`. Each is one field; the table under **One field switches each style** lists every value.
4. **Type your own map** (two minutes): pass `text = [[ ... ]]` to `PP.level`, one character per tile, top row first: `#` ground, `=` plank, `^` spikes, `P` start, `G` goal, `o` gem, `C` checkpoint, `M` moving platform. **Levels from text** lists all of them, saws, lava and springs included.
5. **Add lives**: `PP.player({ lives = 3 })` gives three tries, hearts in the HUD and a GAME OVER card. **Lives, checkpoints and moving platforms** below says how they fit together.
## Your first level (works as written in a brand-new world)
Open `scenes/main.scene/build.luau` and **replace the whole file** with this, then press Play:
```lua
local PP = require("twoDKit.api")
function content()
PP.level({ theme = "grassland", moverLength = 3, moverTravel = 3, text = [[
##############################
#............................#
#....o.......................#
#.......................o....#
#.......................##...#
#...====..........o.....##...#
#.......................##...#
#..P.........C..........##.G.#
##########^^###M.....#########
###############......#########
]] })
PP.player({ character = "fox", feel = "tight", lives = 3 })
PP.hud()
end
```
With `lives = 3` the player has three tries: run out and the HUD shows a GAME OVER card with the run's gems, time and lives lost; TRY AGAIN, or a fresh press of Jump on any device once the card has been up for a beat, starts the run over from the level start with full lives (gems, timer and deaths back to zero). Leave `lives` out for endless respawns at the last checkpoint.
You get a 30 x 10 grassland level with a parallax sky, a fox you control, a checkpoint flag, a row of spikes, a moving platform over a bottomless drop, a wall to climb with wall jumps, three gems, a goal, and a HUD with a **STYLES** button that switches theme, tile set, background, character, feel, camera and HUD style live. Change `theme = "grassland"` to `"cave"`, `"castle"`, `"lab"`, `"snow"`, `"desert"`, `"volcano"`, `"jungle"`, `"coast"` or `"crypt"` and the whole level re-skins.
## Step by step: from a text map to a finished level
Each step is a complete scene script: paste it over your scene's `build.luau` (for a new world, `scenes/main.scene/build.luau`), save, and the editor rebuilds the scene; press Play to try it. Each step adds one thing to the one before.
### 1. Build a level from the text map
Type the level as rows of characters, top row first, all rows the same width. `#` is solid ground (the kit picks the right edge and corner tile for every cell and merges the collision so nothing snags on seams), `.` is empty air, `P` is where players start, `o` is a gem and `G` is the goal.
```lua
local PP = require("twoDKit.api")
function content()
PP.level({ theme = "grassland", text = [[
################################
#..............................#
#..............................#
#..............................#
#..............................#
#..............................#
#..............................#
#..P.......o..........o......G.#
################################
################################
]] })
PP.player({ character = "fox" })
PP.hud()
end
```
The fox runs from `P` to `G` picking up two gems; the HUD counts gems, time and lives (hearts for the lives left) and shows the level-clear card at the goal. The full legend is under **Levels from text** below.
### 2. One-way ledges and moving platforms
`=` is a one-way ledge: jump up through it from below and stand on it; hold Down and press Jump to drop through. `M` is a moving platform that travels sideways (`V` travels up and down), drawn with the tile set's planks; it carries whoever stands on it, and a jump off it keeps its speed. Here it ferries you over a pit; the three `mover` numbers set its width, how far it travels and how fast.
```lua
local PP = require("twoDKit.api")
function content()
PP.level({ theme = "grassland", moverLength = 3, moverTravel = 6, moverSpeed = 2, text = [[
################################
#..............................#
#..............................#
#..............o...............#
#.............====.............#
#..............................#
#.....====.............o.......#
#..P...................##...G..#
##########M.........############
##########..........############
]] })
PP.player({ character = "fox" })
PP.hud()
end
```
For a platform you place by hand instead of in the text (any size, any path), use platformsKit and add `twoDKit.PixelSkin` so it is drawn in the level's style: see **Bring other kits' parts into the pixel style** in the how-to guide.
### 3. Checkpoints, lives and game over
`C` is a checkpoint (touch it and you come back there after a hit), `^` are spikes. `lives = 3` gives each player three lives: losing the last one shows the GAME OVER card, and TRY AGAIN (or a fresh press of Jump) starts the run over from the start with full lives. Leave `lives` out for endless respawns at the last checkpoint. Falling off the bottom of the level costs a life too.
```lua
local PP = require("twoDKit.api")
function content()
PP.level({ theme = "grassland", moverLength = 3, moverTravel = 6, moverSpeed = 2, text = [[
################################
#..............................#
#..............................#
#..............o...............#
#.............====.............#
#..............................#
#.....====.............o.......#
#..P....C.............C#.^^^.G.#
##########M.........############
##########..........############
]] })
PP.player({ character = "fox", lives = 3 })
PP.hud()
end
```
### 4. Swap styles with one setting each
The same level in another style: `theme` switches the tile set and the background together, and every other part takes one setting. Any of these can also change while the game runs, for this player or for everyone (see **One field switches each style**).
```lua
local PP = require("twoDKit.api")
function content()
PP.level({
theme = "volcano", -- tiles and background together
gemLook = "coin", -- crystal, coin, star, cherry, orb, battery
checkpointStyle = "campfire", -- flag, lantern, campfire, banner, beacon
moverLength = 3, moverTravel = 6, moverSpeed = 2,
text = [[
################################
#..............................#
#..............................#
#..............o...............#
#.............====.............#
#..............................#
#.....====.............o.......#
#..P....C.............C#.^^^.G.#
##########M.........############
##########..........############
]],
})
PP.player({ character = "pirate", feel = "classic", camera = "smooth", lives = 3 })
PP.hud({ style = "neon" })
end
```
While playing, the STYLES button (or E / the gamepad's X) cycles every style live, and from code `PP.setTheme("crypt")`, `PP.setCharacter("ninja")`, `PP.setFeel("moon")` and `PP.setCamera("rooms")` do the same.
## Controls
| | Keyboard | Gamepad | Touch |
|---|---|---|---|
| Run | A / D or arrows | left stick or d-pad | d-pad on the left |
| Jump (hold for higher) | Space or K | A | Jump button (or swipe up) |
| Dash (8 directions: hold a direction) | Shift or J | RB or Y | Dash button |
| Drop through a one-way platform | hold Down (S) + Jump, or Crouch (C) + Jump | down + A | down on the d-pad + Jump |
| Open the style gallery | E or L (Interact), or the STYLES button | X | Interact button |
Controls come from controlsKit's `platformer` scheme, so rebinding, button prompts and touch layouts work the controlsKit way (`require("controlsKit.controls")`).
## Levels from text
`Level2D.text` (or `PP.level({ text = ... })`) is the level, top row first. One character is one tile (one world unit, 16 art pixels). The entity's position is the grid's bottom-left corner.
| Char | Becomes |
|---|---|
| `#` | Solid ground. Autotiled: every cell picks the right edge, corner or inner-corner tile from its eight neighbours (47-tile blob). |
| `=` | One-way platform: jump up through it, stand on it, drop down through it. |
| `^` | Spikes, pointing away from the solid next to them. Touching them costs a life (Trapline). |
| `W` | Saw blade: a spinning two-tile buzzsaw. Touching it costs a life. |
| `L` | Lava: an animated pool that bubbles and throws embers. Falling in costs a life. |
| `X` | Crumbling block: solid ground that cracks and shakes when stood on, falls away after half a second and comes back three seconds later. |
| `F` | Fire jet: a steel nozzle that fires up to three tiles away from what it is mounted on, every three seconds, after a sputtering warning. The flame costs a life. |
| `H` | Heart: gives back one Trapline life (once per run, per player); grey while lives are full or off. |
| `D` | Dash crystal: refills a spent dash in the air, then grows back after a second. |
| `T` | Spring: bounces you about six tiles up and gives the dash back. |
| `C` | Checkpoint (a Trapline checkpoint, drawn as a pixel flag that raises when you reach it; `checkpointStyle` picks lantern, campfire, totem banner or sci-fi beacon instead). |
| `P` | Player start. |
| `M` / `V` | Moving platform side to side / up and down (platformsKit `pingpong`), drawn as the tile set's planks. You ride it. |
| `o` | Gem to collect (per player, counted in the HUD; `gemLook` picks crystal, coin, star, cherry, orb or battery). |
| `G` | Goal: shows the level-clear card with gems, time and lives lost. |
| `*` | A decoration on this floor tile (others are scattered by `seed`). |
| `B` | Back wall: a darker fill behind the level, no collision. |
| `.` or space | Empty. |
Outside the grid counts as solid, so the border reads as one mass. Collision is built from merged rectangles (no seams to catch on). A Trapline kill zone sits `killDepth` tiles below the bottom row, so a fall costs a life and you come back at your last checkpoint. `Level.parse`, `Level.tiles`, `Level.rects` and `Level.mask` in `twoDKit.level` are there for your own tools.
## Lives, checkpoints and moving platforms
They come from three kits, and the kit wires them together for you:
- **Checkpoints** (`C` in the map) are Trapline checkpoints drawn in the kit's pixel art (`checkpointStyle`: flag, lantern, campfire, banner or beacon). Touching one makes it your respawn point: it lights up with a glow, embers and a chime, the HUD shows a CHECKPOINT toast, and it stays lit for you (each player has their own).
- **Dying** happens on spikes, saws, lava and fire jets, or by falling `killDepth` tiles below the bottom row. You come back at your last checkpoint, or at `P` if you have none.
- **Lives** are off unless you ask: `PP.player({ lives = 3 })`. Without lives every death just respawns you. With lives, the HUD shows hearts for the lives left, a heart pickup (`H`) gives one back, and losing the last one shows the GAME OVER card; TRY AGAIN (or Jump) restarts the run from `P` with full lives and the checkpoints cleared.
- **Moving platforms** (`M` side to side, `V` up and down; `moverLength`, `moverTravel` and `moverSpeed` set their size, distance and speed) are platformsKit platforms. They carry you while you stand on them, keep their speed when you jump off, and run on a shared clock so every player sees them in the same place. A checkpoint is a point in the level, never on a platform: if you die after riding one, you come back at the checkpoint, not on the platform.
- **Crumbling blocks** (`X`) break and come back for everyone; **gems, hearts and dash crystals** are per player.
## Ability gates and joined rooms (metroidvania)
Two moves are off by default so a game can hand them out as upgrades, and rooms can be joined into one map:
- **Double jump**: `Player2D.airJumps` (or `PP.player({ airJumps = 1 })`) is how many jumps you get in mid-air; they refill on landing and on a wall, like the dash. Each is the feel's `airJumpHeight` (85% of `jumpHeight` by default) and plays a wing-beat puff with a higher jump sound.
- **Down-slam**: `Player2D.canSlam` (or `PP.player({ canSlam = true })`). Press down in the air and you drive straight down at the feel's `slamSpeed` (30 tiles/s) until you hit the ground: a dust ring, a heavy shake and a hard-landing thud. Down + jump on a one-way platform still drops through.
- **Joined rooms**: `Level2D.edgeWalls = false` (or `PP.level({ edgeWalls = false })`) leaves out the invisible walls past a level's left and right edges. Put the next level at this one's x + width with a gap in the touching edge columns and you walk across; stack one under another with a gap in the floor and ceiling rows to fall and jump between them (`killDepth = 0` on the upper room). The camera clamps to whichever room you are in and only that room draws its background.
- **React to them**: `twoDKit.events` fires `airJump`, `slam` and `slamLand` on every peer (payload `player`, `x`, `y`, `isLocal`, and `ground` on `slamLand`: the entity the slam hit), so a breakable floor or a boss can listen: `require("twoDKit.events").on("slamLand", function(e) ... end)`. `Player2D:state()` also gives `airJumpsLeft`, `slamming`, `slamGround` and `slamAt`.
So a level with a moving platform over a pit, a checkpoint after it and `lives = 3` plays like this: fall off the platform and you lose a heart and start again before the pit; cross it, touch the checkpoint, and a later fall brings you back after the pit instead.
## When the editor and play look different
| What you see in the editor | Why, and what to do |
|---|---|
| The level looks soft or the background sits at a different depth. | The editor's fly camera is a perspective camera; in play the kit's pixel-perfect camera takes over, and that is the picture players get. Judge pixel crispness in play. |
| There is no player, camera or HUD. | They are made from the player template when play starts (every person who joins gets their own). Press Play. |
| Moving platforms stand still, checkpoints are unlit, saws and fire jets are idle. | They run in play only. Their start positions in the editor are where they begin. |
| A style chosen in the STYLES panel is gone after play. | The panel changes your own view for this play session. To keep a style, set its field in `build.luau` (`PP.level({ theme = ... })` and so on). |
| After an edit to `build.luau` the level did not change. | Save the file: the scene rebuilds on save. If you are in play, stop and press Play again. |
| The editor says a component "is waiting for content it requires". | Seen right after installing, while files arrive. It clears by itself. |
| A theme you just added is missing from the Style Hall. | The hall builds its rooms when the scene loads. Reload the scene, or press Play again. |
## One field switches each style
| What | Field | Values |
|---|---|---|
| Theme (tile set + background) | `Level2D.theme` | `grassland`, `cave`, `castle`, `lab`, `snow`, `desert`, `volcano`, `jungle`, `coast`, `crypt`, `sky`, `factory`, `candy`, `autumn` |
| Tile set | `Level2D.tileset` | the fourteen above, or `auto` (follow the theme) |
| Background | `Level2D.background` | the fourteen above, `auto`, or `none` |
| Character | `Player2D.character` | `knight`, `robot`, `fox`, `mage`, `ninja`, `astronaut`, `frog`, `pirate`, `skeleton`, `viking`, `slime`, `bird` |
| Movement feel | `Player2D.feel` | `tight`, `floaty`, `heavy`, `slippery`, `classic`, `nimble`, `moon`, `retro`, `snappy`, `bouncy`, `glide` |
| Camera | `Camera2D.style` (or `Level2D.camera` for one level) | `pixelPerfect`, `smooth`, `rooms` |
| HUD style | `Hud2D.style` (or `PP.hud({ style = ... })`) | `pixel` (default), `gameboy`, `parchment`, `neon`, `minimal`, `arcade`, `wood`, `comic` |
| Gem look | `Level2D.gemLook` | `crystal` (default), `coin`, `star`, `cherry`, `orb`, `battery` |
| Checkpoint look | `Level2D.checkpointStyle` | `flag` (default), `lantern`, `campfire`, `banner`, `beacon` |
Each tile set has ground, edges, outer and inner corners, a back wall, one-way platform ends, spikes in four directions and eight decorations. Each background has four parallax bands (sky, far, mid, near). Each character sheet has idle, run, jump, fall, wall slide, dash, land and hurt. In play, `PP.setTheme(id)`, `PP.setCharacter(id)`, `PP.setFeel(id)` and `PP.setCamera(style)` switch them from code.
## Every style, pictured
All pictures are taken in play through the kit's own camera, on the showcase's first level with only the one field changed.
**Themes** (`theme`): each one is its own tile set, spikes, planks, decorations and four-layer background.
| | |
|---|---|
|  `grassland` |  `cave` |
|  `castle` |  `lab` |
|  `snow` |  `desert` |
|  `volcano` |  `jungle` |
|  `coast` |  `crypt` |
|  `sky` |  `factory` |
|  `candy` |  `autumn` |
**Characters** (`character`), idle and running, from the top left: knight, robot, fox, mage, ninja, astronaut, frog, pirate, skeleton, viking, slime, bird.

**HUD looks** (`style`):
| | |
|---|---|
|  `pixel` |  `gameboy` |
|  `parchment` |  `neon` |
|  `minimal` |  `arcade` |
|  `wood` |  `comic` |
**Hazards and pickups** in the castle theme: a crumbling block, a spring, a heart, spikes, a dash crystal, lava and a fire-jet nozzle.

## The movement feels
Each feel is built around one idea, and the numbers below are measured from the motor (the test suite holds them to it):
| Feel | Plays like | Full jump / time in the air | Reaches top speed | Stops within | Running jump | Falls 8 tiles |
|---|---|---|---|---|---|---|
| `tight` | Celeste-like: instant, precise, short hop on a tap, fast 3.5-tile dash. | 3.6 tiles / 0.72 s | 0.08 s | 0.17 tiles | 5.0 tiles | 0.60 s |
| `floaty` | Low gravity: twice the hang time, a slow fall you can steer, a long slow dash. | 4.5 tiles / 1.58 s | 0.12 s | 0.24 tiles | 7.9 tiles | 1.15 s |
| `heavy` | Weighty: winds up slowly, carries momentum, short committed jumps that slam down, little air control. | 3.1 tiles / 0.60 s | 0.45 s | 0.70 tiles | 3.9 tiles | 0.45 s |
| `slippery` | On ice: slow to get going, slides about 3.5 tiles to stop, slow to turn, momentum carries. | 3.4 tiles / 0.73 s | 0.48 s | 3.5 tiles | 5.9 tiles | 0.65 s |
| `classic` | Momentum platforming: builds up to a high top speed, slides a tile when you let go, big jumps you can steer. | 4.4 tiles / 0.87 s | 0.33 s | 1.1 tiles | 7.4 tiles | 0.63 s |
| `nimble` | An acrobat: two dashes per jump, high wall jumps off slow wall slides, instant and light. | 3.2 tiles / 0.70 s | 0.07 s | 0.17 tiles | 5.3 tiles | 0.65 s |
| `moon` | Barely any gravity: six-tile jumps that last almost three seconds, a slow drift down, gentle steering. | 6.2 tiles / 2.65 s | 0.15 s | 0.3 tiles | 11.9 tiles | 1.80 s |
| `retro` | 8-bit committed jumps: the same arc however long you hold, almost no steering in the air, instant on the ground. | 3.5 tiles / 0.72 s | 0.03 s | 0.04 tiles | 3.9 tiles | 0.68 s |
| `snappy` | Arcade-sharp: full speed on the first frame, dead stops, a short sharp hop that drops fast. | 3.0 tiles / 0.47 s | 0.02 s | 0 tiles | 4.2 tiles | 0.42 s |
| `bouncy` | Springy: a real fall bounces you back up, and a jump pressed as you land springs about a third higher. | 3.5 tiles / 0.75 s | 0.13 s | 0.35 tiles | 5.3 tiles | 0.63 s |
| `glide` | A glider: hold jump while falling to drift down slowly and steer across long gaps; let go to drop. | 3.4 tiles / 2.28 s | 0.10 s | 0.25 tiles | 14.8 tiles | 0.63 s (4.5 s holding jump) |
Every number is data in `twoDKit.feels` (run speed, accelerations, jump height, rise / fall / cut gravity, apex hang, coyote time, jump buffer, wall slide speed, wall jump launch and lock, dash speed, time, count and cooldown, and how fast speed above the top speed bleeds off after a dash). Make your own: `PP.registerFeel("moon", { jumpHeight = 6, fallGravity = 15 })`.
## Pixel-perfect camera
`Camera2D` is the player's camera behaviour. The view height is always the window height divided by a whole number of screen pixels per art pixel (chosen so about `targetHeight` = 216 art pixels show, and at least about `minWidth` = 240 wide, so a phone held upright still sees the level), and the view is snapped to the pixel grid, so every art pixel is the same whole number of screen pixels at any window size, odd sizes included: no shimmer, no uneven pixels. The parallax backgrounds scroll in whole screen pixels on the same grid, so their pixels are as crisp as the tiles'. The test suite checks this at fourteen window sizes from a phone to 4K. While `crisp` is on it also turns off temporal and edge antialiasing and holds render scale at 1 on that peer. It never shows anything outside the level the player is in: when a level is smaller than the view would be (the 10-row first example on a 1080p window, say), the zoom goes up by whole steps until the whole view fits inside it, and the final pixel snap is kept inside the level's edges too. Styles: `pixelPerfect` (dead zone, snapped to the art grid), `smooth` (eased with look-ahead), `rooms` (holds a `roomWidth` x `roomHeight` room and slides to the next).
## Bring your own art
- **A character sheet**: any material on the `pixelSprites.sprite` shader (nearest-filtered texture). Register it and name it in `Player2D.character`:
```lua
local PP = require("twoDKit.api")
PP.registerCharacter("hero", {
material = asset.resolve("myArt.hero", "material"),
frameWidth = 32, frameHeight = 32, columns = 8, rows = 8,
anims = { idle = { row = 0, frames = 4, fps = 6, loop = true }, run = { row = 1, frames = 6, fps = 12, loop = true } },
})
```
Frames are read left to right from the top-left; the character faces right, feet on the frame's bottom row, centred. Missing animations fall back (wall slide to fall, fall to jump, jump to idle, dash to run), so idle + run is enough to start.
- **A tile set**: a 128 x 128 atlas of 16 px tiles in the layout `twoDKit.autotile` documents (cells 0-46 blob ground, 47 back wall, 48-51 one-way, 52-55 spikes, 56-63 decorations), then `PP.registerTileset(id, { material = ... })`.
- **A background**: four 320 x 180 images that repeat horizontally, each on a material using the `pixelParallax.parallax` shader, then `PP.registerBackground(id, { layers = { { material = sky, factor = 0.04 }, ... } })`.
- **Generate art in code**: the **pixelPaint** package (`twoDKit.paint` is the kit's name for it) is the raster painter all the kit's art was made with (rects, lines, ellipses, polygons, ordered dither, gradients, outlines, ASCII sprites, seeded noise, `Paint.save` to a nearest-filtered texture, `Paint.material`). The kit's own generators are in `artgen/` (`tilesets`, `characters`, `backgrounds`, `fx`, `pickups`, `hazards`, `juicefx`): run `require("twoDKit.artgen.tilesets").generate("cave")` to repaint one. They stay in the kit because they paint the kit's own catalogue.
## Game feel and sound
Every moment has a pixel effect and an 8-bit sound out of the box, on every peer, for every player it sees (others' sounds quieter, fading with distance), driven by synced animation changes and Trapline's events, so it adds no network traffic. Jumps stretch, landings squash (a fall of 5 tiles or more lands hard: a wide dust cloud and a small shake), wall jumps kick dust, dashes leave speed lines and distinct after-images, starting to run or turning kicks up dust and wall slides scrape specks off the wall. A death flashes the body white, bursts it into pixels, shakes the camera and holds a 75 ms hit stop for that player; gems pop. A checkpoint lights up with a warm glow that blooms and then pulses, two waves of embers and a chime. Reaching the goal is a win: time slows to 0.3 for a moment and eases back, fireworks and confetti burst over the goal, the character hops twice, and only then does the level-clear card come up. A glide leaves sparkles, and hearts, dash crystals and springs each have their own burst and sound. Squash and stretch is drawn by the sprite shader at art-pixel resolution, so it never blurs. The `pixelPerfect` and `smooth` cameras rest at the height of the ground you last stood on, so jumping does not bob the view; they follow you down when you fall past the dead zone and ease between heights at ledges.
- Sounds: jump, land, hard landing, dash, wall jump, gem, checkpoint, death, game over, level clear and a UI click, synthesised from square, triangle and noise voices by the **chipSfx** package (`twoDKit.sfx` is the kit's name for it) and shipped as clips. `Player2D.sfxVolume` (0.55) and `Player2D.sound` set the volume and mute; `require("twoDKit.sfx").play("click")` plays one from your own UI.
- Tuning: `require("twoDKit.juice")` holds `enabled`, `shake`, `hitstop` and `HARD_LAND_DROP`; `Sprite2D.effects` and `Sprite2D.squash` switch them per sprite.
- Hooks: `require("twoDKit.events").on("gem", fn)` hears jump, land, dash, wallJump, gem, checkpoint, death, gameOver, restart and goal (or `"*"`), each with the player, where it happened and whether it is your own.
## Multiplayer
Every peer builds the same level from the same text on its own temporary entities, so nothing about the level crosses the network. Each player's body is moved only by its owner; the engine replicates its pose to everyone, and the Sprite2D's `character`, `anim`, `facing` and `blink` are synced fields, so every peer draws every player with the right animation. Dash flash and after-images, the hurt fade, jump, wall-kick and landing dust are derived from those fields on each peer, and on someone else's player each animation change waits the engine's pose smoothing delay so it lines up with the smoothed body. Lives and checkpoints are per player through Trapline; after a respawn the character is back upright, facing the camera and looking exactly as before, for every player watching; moving platforms run on platformsKit's shared clock. Style choices in the gallery: character and feel are per player and seen by everyone; tile set, background, theme and camera are each peer's own view.
## What is inside
| Asset | What it does |
|---|---|
| `api` | The front door: `PP.level`, `PP.player`, `PP.hud`, `PP.startOf`, the `register*` functions and the in-play switches. |
| `Level2D` (component) | A level from text: tiles, collision, markers, parallax. |
| `Player2D` (component) | The platformer motor (box sweeps with the engine's `Physics.boxCast`, one-way colliders, riding moving platforms), animation choice, spikes, gems, goal, run timer. |
| `Sprite2D` (component) | An animated sprite from a sheet, facing left or right, pixel-snapped; motion effects. |
| `Camera2D` (component) | The pixel-perfect camera behaviour (tagged `cameraBehavior`). |
| `Hud2D` (component) | Gems / time / lives (hearts for the lives left when Trapline lives are on, else lives lost; the gem counter bumps on each gem, a CHECKPOINT toast on each new checkpoint), animated level-clear and GAME OVER cards with TRY AGAIN (or Jump, after a short beat) when Trapline lives run out, STYLES gallery and level travel. One `style` setting picks its look: `pixel`, `gameboy`, `parchment`, `neon` or `minimal` (`Catalog.hudStyleList`). |
| `PixelSkin` (component) | Draws a Trapline saw or a platformsKit platform you place yourself as pixel art that matches the level (a pixel buzzsaw on a track; the tile set's planks). |
| `catalog`, `feels` | Every style as labelled data, and the registries for your own. |
| `traps` | Saw blades, lava, crumbling blocks, fire jets, hearts, dash crystals and springs from the level text (`W L X F H D T`). |
| `level`, `autotile` | Text parsing, blob autotiling, merged collision rectangles, spike boxes. |
| `sprites`, `parallax` | The kit's names for the **pixelSprites** and **pixelParallax** packages (installed with it, and installable on their own): sprite quads with flash, fade, tint and squash, and pixel-crisp parallax bands, plus `SpriteSheet` and `ParallaxBackground` components for games that don't use the rest of the kit. |
| `fx`, `view`, `levels` | pixel effects, the shared camera view, the live registry of levels and players. |
| `juice`, `sfx`, `events` | Game feel (each moment's effect, sound, shake, hit stop and squash curve), the kit's name for the **chipSfx** 8-bit sounds, and the moments event bus. |
| `paint`, `artgen/*` | The kit's name for the **pixelPaint** painter, and the generators for every texture in `art/`. |
| `pixelSprites.sprite`, `pixelParallax.parallax` (shaders, in those packages) | Unlit alpha-cut pixel shaders; the frame of a sheet is picked per entity, so one material draws every sprite on a sheet. |
| guides | `how-to-make-a-2d-platformer-tilemap-from-text-wall-jump-dash-pixel-perfect-camera` and `example-2d-platformer-level-from-an-empty-world`. |
| `twoDKitTests` (test suite) | Parsing, autotiling, collision merging, feels, catalog, motor and level build checks. |
## Guides
- `guides { path: "twoDKit.package/how-to-make-a-2d-platformer-tilemap-from-text-wall-jump-dash-pixel-perfect-camera" }`: how to use every part.
- `guides { path: "twoDKit.package/example-2d-platformer-level-from-an-empty-world" }`: from an empty world to a small playable level with checkpoints, a hazard and a moving platform.
## Notes and limits
- The body has no rigid body: the motor writes its position, so it is not affected by #11892 (setting velocity on a player's own body can do nothing) and does not use the built-in CharacterController (whose capsule rounds off ledges and has no acceleration curves, wall slide or jump cut).
- Players pass through each other (as in Celeste); Trapline hazards and kill zones you place yourself work with the kit's player as with any player.
- Two engines signed in to one account count as one player (#14448): test multiplayer with two accounts.
- Dependency versions. An install of 1.2.2 brings Trapline 1.5.4 at exactly that build, because the kit's own files name it; Trapline 1.5.4 is a released Trapline (the `none` checkpoint look the kit's pixel checkpoints use, merged on Trapline's world from pull request #3), and Trapline's own 70 tests pass on it. pixelSprites, pixelParallax, pixelPaint and chipSfx live in this kit's own world and arrive at their newest release (a fresh install on the day of release brought 1.0.3, 1.0.3, 1.0.1 and 1.0.1). controlsKit and platformsKit are named only in `package.yaml`, and an install brings each one's newest published release rather than the version this kit's world held (engine issue #19270). This release was tested with controlsKit 1.2.3 and platformsKit 1.5.5 here, and platformsKit 1.5.8 in a fresh install. Trapline and platformsKit bring the kits they are built on: SecondWind 1.4.4, Lifeline 1.0.1, barsKit 1.4.3, juiceKit 1.2.8 and MatchFlow 1.3.1. `zeromind.update` keeps a dependency at its version when the new one would leave a file of this kit not loading or holding a new error; it does not play the kit, so after updating any of them, `zero tests run twoDKitTests` confirms that movement, levels and styles still behave the same.
- A world that already held Trapline 1.4 kept the SecondWind 1.2.0, barsKit 1.2.0 and juiceKit 1.2.1 copies that install placed through later Trapline updates (engine issue #23583). Updating Trapline to the 1.5.4 build removed them in this kit's own world, and Trapline 1.5.4's dependency check reads the copies Trapline runs rather than whatever a name finds, so its tests pass either way. A world without an earlier Trapline gets only the versions above.
## Changelog
- **1.3.4**: the player and the HUD read controlsKit 1.2.8, the release every package that ships with sideScrollerKit (menusKit, saveKit, abilitiesKit, interactKit, navUiKit, slash2D) moves to together, so a world installing them holds one controlsKit. No gameplay change.
- **1.3.3**: the controls test passes wherever twoDKit is installed. In a world holding several controlsKit builds a registered scheme can land in another build than the player reads; the test now checks what matters there, that the player ends up on a scheme with move and jump. No gameplay change.
- **1.3.2**: a player can always run and jump. When `Player2D.scheme` names a scheme the controlsKit build twoDKit reads does not hold (not registered yet, or registered in another build of controlsKit the world also holds), the player runs on the stock `platformer` scheme and tries the named scheme again every half second; 1.3.1 stayed on controlsKit's default twin-stick scheme, where move works and jump does not. New `PP.registerScheme(name, scheme)` registers a kit's own scheme in the build twoDKit reads. Two tests cover both.
- **1.3.1**: the player and the HUD read controlsKit 1.2.4, the same build sideScrollerKit, slash2D, abilitiesKit and interactKit read. 1.3.0 read 1.2.3, so a world holding both builds ran two input loops that kept resetting each other, and a player made with another kit's control scheme never moved. The dependency now states controlsKit 1.2.4.
- **1.3.0** (published from pull requests #4 and #5, used by metroidvaniaKit): three opt-in features a metroidvania needs, all off by default so existing levels and players play exactly as before.
- Double jump: `Player2D.airJumps` (motor `opts.airJumps`, `PP.player({ airJumps = n })`): mid-air jumps of the feel's `airJumpHeight` (default 85% of `jumpHeight`), refilled on landing and on a wall like the dash. Moment `airJump`: a wing-beat puff and the jump sound pitched up.
- Down-slam: `Player2D.canSlam` (motor `opts.canSlam`, `PP.player({ canSlam = true })`): a fresh press of down in the air drives straight down at the feel's `slamSpeed` (default 30) until the ground. Moments `slam` and `slamLand` (`ground` = what it landed on): a dust ring, a heavy shake and the hard-landing sound. Drop-through on one-way platforms is unchanged.
- The new moments reach every peer through Player2D's synced `move` field and fire on `twoDKit.events` (`airJump`, `slam`, `slamLand`); `Player2D:state()` adds `airJumpsLeft`, `slamming`, `slamGround`, `slamAt`, `clock`. Sprite2D no longer plays the ground jump's dust for an air jump.
- Joined rooms: `Level2D.edgeWalls` (default true; `PP.level({ edgeWalls = false })`) leaves out the invisible edge walls so rooms placed side by side or stacked are walked, fallen and jumped between; with it off the kill zone spans only the level's width, so it never sits under a neighbour.
- Tests for air jumps, the slam (and drop-through with it on) and joined rooms.
- **1.2.2**: "Which version did I get?" and the notes say what a fresh install really brings: Trapline held to 1.5.4, and pixelSprites, pixelParallax, pixelPaint and chipSfx at their newest release (found by installing 1.2.1 in a new world).
- **1.2.1**: preview pictures for the new backgrounds (no change to the kit's code or art).
- **1.2.0**: more life, better defaults, more to choose from.
- Look and feel: landings kick dust to both sides and squash a little longer; checkpoints light up with a blooming, pulsing glow, embers and a chime; the goal plays a slow-motion win with fireworks, confetti and a victory hop before the level-clear card; gliding leaves sparkles; the `pixelPerfect` and `smooth` cameras rest at the ground you last stood on, so jumps no longer bob the view, and ease at ledges.
- Defaults: `PP.level()` with no options builds a starter level, so `PP.level() PP.player() PP.hud()` is a whole game. `PP.VERSION` names the kit's version.
- Variety: themes `sky`, `factory`, `candy`, `autumn` (14); characters `skeleton`, `viking`, `slime`, `bird` (12); feels `snappy`, `bouncy`, `glide` (11); HUD looks `arcade`, `wood`, `comic` (8); hazards `W` saw, `L` lava, `X` crumbling block, `F` fire jet; pickups `H` heart, `D` dash crystal, `T` spring.
- Parts: the painter is the **pixelPaint** package and the 8-bit sounds are the **chipSfx** package, each installable on its own (`twoDKit.paint`, `twoDKit.sfx` and `twoDKit.artgen.sfx` still work). Trapline 1.5.4 is now a released Trapline.
- Docs: a five-minute walkthrough, "Which version did I get?", how lives, checkpoints and moving platforms fit together, what differs between the editor and play, and a picture of every theme, character, HUD look and the hazards.
- **1.1.11**: built on Trapline 1.5.4 (Trapline's pull request #3, which supersedes #2): the same `none` checkpoint look, now with one version everywhere and a dependency check that reads the copies Trapline runs, so all 70 of Trapline's own tests pass where 1.1.10's Trapline build failed 2. Checkpoint lanterns and flags still light, and an install still loads Trapline's api at one release. No change to the kit's own code.
- **1.1.10**: a rider keeps its footing on a lift on every frame, also when the lift's collider catches up into the feet or, after a frame hitch, drops away from feet carried onto where it was (on moving ground the ground probe looks again from above, and a small outside move that leaves the feet inside the lift settles onto it instead of starting the body again from rest), with a regression test; a 30 s ride up and down the showcase lift shows 0 airborne frames (1.1.9: about 1 in 200). A fresh install lands Trapline.api at one release: this kit's world holds Trapline exactly as the build of pull request #2, so the kit and Trapline share one api and its checkpoint list (the 1.1.9 flag fallback stays for worlds that hold another Trapline copy). The package description names the right version.
- **1.1.9** (pull request #3, released as part of 1.1.10): riding a moving platform no longer loses footing or falls through it when it stops (a platform's collider can trail its entity by a frame; the new `Motor.settle` puts the feet back on its real top after a carry, and the ground probe reaches further on moving ground), with a regression test. Hud2D shows the lives left as hearts when Trapline lives are on (lives lost otherwise). Checkpoint flags light up again when an install lands Trapline.api at two releases (Level2D also reads the player's synced Trapline.Runner, not only `TL.hasReached`, whose list is private to each copy of the api). In edit mode the parallax background fills a perspective editor camera's view instead of showing as a box behind the level (`View.current()` sizes a perspective camera's view from its fov, and Level2D scales the bands for their depth).
- **1.1.7**: this changelog; pixelSprites and pixelParallax 1.0.3 (their changelogs). No change to the kit's code.
- **1.1.6**: Notes and limits say which dependencies an install holds to a build (pixelSprites, pixelParallax, Trapline) and which arrive at their newest release (controlsKit, platformsKit), and the versions this release was tested with.
- **1.1.5**: the old-Trapline-copies limit cites engine issue #23583; the closed #22971 is no longer listed as a limit.
- **1.1.4**: dependency versions corrected (platformsKit 1.5.5, not 1.5.1) and the kits Trapline and platformsKit bring are named; the install note cites #21420.
- **1.1.3**: the first example says the STYLES panel also switches HUD style (found by following it word for word in a new world).
- **1.1.2**: README and guides cover all 8 characters and 8 feels, the HUD styles and the gem and checkpoint looks; built on the engine's library d4061d2 and Trapline 1.5.3.
- **1.1.1**: installs again in a new world (1.1.0 had an optional juiceKit require that the install check refused); hit stop uses the engine's time scale.
- **1.1.0**: game feel and 8-bit sound; 10 themes, 8 characters, 8 feels, 5 HUD styles, 6 gem and 5 checkpoint looks; finished level-clear and game over cards; sprites and backgrounds released on their own as pixelSprites and pixelParallax.
# pickups
Paints every gem look and checkpoint look of the twoDKit as pixel-art sprite sheets and saves them to `art/fx/` as nearest-filtered textures with `sprite`-shader materials. `Level2D` draws its `o` gems from `gems` (setting `gemLook`) and its `C` checkpoints from `checkpoints` (setting `checkpointStyle`). Run it again whenever the art code or the look lists change.
```luau
local Pickups = require("twoDKit.artgen.pickups")
Pickups.generate() -- saves art/fx/gems and art/fx/checkpoints (+ materials)
local gems = Pickups.gemSheet() -- canvases only, for previews
local cps = Pickups.checkpointSheet()
```
The row layout is data in `twoDKit.catalog`: `Catalog.gemLooks[id]` and `Catalog.checkpointLooks[id]` give each look's `row` (its idle loop), and `row + 1` holds its collect burst (gems) or its reached loop (checkpoints). The lists `Catalog.gemLookList` and `Catalog.checkpointLookList` give the order, and `gemLookLabels` / `checkpointLookLabels` the names to show.
## `gems`: 128x192, 16x16 frames, 8 columns
Identity: `twoDKit.art.fx.gems`.
| Look | Rows | Idle | Burst (6 frames) |
|---|---|---|---|
| `crystal` | 0, 1 | 6 frames, the faceted cyan and violet gem of `art/fx/fx` (copied, so the default is unchanged) | crystal shards |
| `coin` | 2, 3 | 8 frames, a gold coin spinning through edge-on | gold glints |
| `star` | 4, 5 | 8 frames, a pink star with eyes that wobbles and twinkles | pink sparkles |
| `cherry` | 6, 7 | 8 frames, two cherries swinging on their stems, leaf fluttering | juice drops that fall |
| `orb` | 8, 9 | 8 frames, a blue soul flame with a white core and eyes, embers drifting up | wisps that rise |
| `battery` | 10, 11 | 8 frames, a power cell charging up, sparks when full | electric sparks |
## `checkpoints`: 128x320, 16x32 frames, 8 columns
Identity: `twoDKit.art.fx.checkpoints`. The ground is the bottom pixel row.
| Look | Rows | Idle | Reached |
|---|---|---|---|
| `flag` | 0, 1 | 4 frames, grey flag hanging low (copied from `art/fx/checkpoint`) | 8 frames, red and gold flag waving at the top |
| `lantern` | 2, 3 | 8 frames, dark brass lantern swinging on an iron crook | 8 frames, flickering flame and a warm halo |
| `campfire` | 4, 5 | 8 frames, cold logs, a sword planted in them, a wisp of smoke | 8 frames, roaring flames and rising sparks |
| `banner` | 6, 7 | 8 frames, carved totem with a limp grey banner | 8 frames, glowing eyes and a waving royal banner with a gold emblem |
| `beacon` | 8, 9 | 8 frames, metal pylon, dark lamp, red standby blink | 8 frames, spinning cyan lamp, light rays, energy climbing the column |
All pixels are fully opaque or fully clear, as the alpha-cut sprite shader needs; glows are dithered. Every look carries a dark outline so it reads on every theme.
# level
Turns a platformer level typed as rows of text characters into a tilemap: a grid of cells, the tile list (with the right autotiled edge and corner tile in every ground cell, one-way platform ends, spikes facing away from their wall, scattered decorations), the mesh data to draw it, merged collision rectangles with no inner seams, spike hit tests and the list of things placed in it (start, checkpoints, gems, goal, moving platforms). Pure data and maths: it spawns nothing.
`twoDKit.Level2D` is the component that builds a playable level from this; call the module directly for tools, tests, or a level built your own way.
## Text format
Rows are read top to bottom; cell (x, y) counts x from the left and y from the BOTTOM row, from 0. One character is one world unit (16 art pixels). Default legend (`Level.DEFAULT_LEGEND`, pass your own to `parse`):
| Char | Kind | Char | Kind |
|---|---|---|---|
| `#` | solid ground | `=` | one-way platform (jump up through it) |
| `^` | spikes | `B` | back wall (drawn behind, no collision) |
| `P` or `S` | player start | `C` | checkpoint |
| `M` | moving platform, side to side | `V` | moving platform, up and down |
| `o` | gem | `G` | goal |
| `*` | forced decoration | `.` or space | empty |
`#`, `=`, `^` and `B` become cells; the rest become markers. Unknown characters count as empty and are reported. A marker inside a back-wall shaft keeps the wall behind it.
## API
- `parse(text, legend?) -> (Grid, problems)`: `Grid = { width, height, cells, markers, text }`, `cells[y + 1][x + 1]` one of `"solid"`, `"oneway"`, `"spike"`, `"back"`, `"empty"`; markers are `{ kind, x, y, char, index }`.
- `kind(grid, x, y, outside?)`: the cell kind; outside the grid counts as solid unless `outside` is given. `isSolid(grid, x, y)`.
- `mask(grid, x, y)`: eight-neighbour mask for `twoDKit.autotile`.
- `spikeDir(grid, x, y)`: `"up"`, `"down"`, `"left"` or `"right"`, away from the solid it is fixed to.
- `tiles(grid, { decorChance?, seed? })`: every tile to draw `{ x, y, tile, z }`; decorations grow on empty cells above ground, placed by a deterministic hash of `seed`.
- `meshData(tiles, name?)`: positions / normals / uvs / indices for `renderer.mesh.create`, in level-local units.
- `rects(grid, kind)`: cells of one kind merged into few rectangles `{ x, y, w, h }` (one-way runs stay one row tall).
- `spikeBox(dir)`, `spikeHit(grid, x0, y0, x1, y1)`: spike danger boxes and a level-local overlap test.
- `toText(grid)`: the grid as text again.
```luau
local Level = require("twoDKit.level")
local grid, problems = Level.parse([[
..P.......o.........G.
.......====......####.
....C..^^......M......
######################
]])
local mesh = renderer.mesh.create(Level.meshData(Level.tiles(grid, { seed = 3 })))
for _, r in Level.rects(grid, "solid") do print(r.x, r.y, r.w, r.h) end
```
# tilesets
Procedural generator for the twoDKit's fourteen pixel-art tile sets: `grassland`, `cave`, `castle`, `lab`, `snow`, `desert`, `volcano`, `jungle`, `coast`, `crypt`, `sky`, `factory`, `candy` and `autumn`. It paints each one into a 128x128 atlas of 16x16 tiles that follows the `twoDKit.autotile` layout exactly, then saves it as a nearest-filtered texture with a sprite material under `twoDKit.package/art/tiles/<id>`.
```luau
local Tilesets = require("twoDKit.artgen.tilesets")
Tilesets.generate() -- paint and save all fourteen (deterministic)
Tilesets.generate("snow") -- just one
local canvas = Tilesets.paint("cave") -- the atlas as a Paint canvas, not saved
print(Tilesets.ids) -- { "grassland", "cave", "castle", "lab", "snow", "desert", "volcano", "jungle", "coast", "crypt", "sky", "factory", "candy", "autumn" }
```
Each atlas holds:
- **0..46**: blob-autotile ground tiles. A shared geometry pass works out, for each pixel, how far it is from each exposed side, then rounds the outer corners and folds the inner corners into a square (masonry) or a diagonal wedge (organic). Each set then shades from those distances: a surface cap on top (grass lip with blades, mossy rim, coping stones, hazard-striped plating, a snow drift, a sand ridge), a dark rim on the sides and bottom, light from the top-left, and its own silhouette (grass blades, a jagged cave ceiling, icicles, a castle coping lip). The interior fill is a 16 px self-seamless texture, so runs of tiles join with no seams.
- **47**: a back wall, a darker, low-contrast version of the fill.
- **48..51**: a one-way platform (left end, middle, right end, single), a thin ledge at the top of the cell.
- **52..55**: spikes pointing up, down, left and right, each with its base on the matching edge of the cell.
- **56..63**: eight decorations standing on the bottom edge of the cell, each with a 1 px outline.
To add a set, write a builder returning `{ round, ink, diagCorners?, fill, sil?, ground, back, platform, spike, decor }` and register it in `builders` and `ids`.
# sprites
Draws a flat pixel-art picture showing one cell of a sprite sheet on any entity, without a component: pick the cell, mirror it, flash it white, dither-fade it, tint it, and keep it snapped to the art's pixel grid so it never shimmers. It is the shared drawing code behind `twoDKit.Sprite2D`, the level's gems, flags and moving-platform planks, and the kit's effects.
`attach` spawns a temporary child entity under the host (so every peer draws its own and nothing is saved) holding a quad pivoted at the bottom-centre of the frame, one world unit per 16 art pixels (`Sprites.PPU`). The material must use the kit's `twoDKit.sprite` shader; the cell, flip, flash, fade and tint are written to the child's per-entity shader data lanes, so one material serves every sprite on the same sheet.
## API
- `Sprites.attach(hostId, opts) -> View`: opts: `material` (required), `frameWidth`, `frameHeight` (pixels, default 16), `columns`, `rows` (default 1), `z` (depth offset), `snap` (default true), `pivotX`, `pivotY` (0..1, default 0.5, 0), `name`, `scale`.
- `Sprites.setCell(view, col, row, flip?)`: show cell (col, row) counted from the top-left; `flip` mirrors horizontally.
- `Sprites.setFlash(view, 0..1)`: mix toward white (hit flash).
- `Sprites.setFade(view, 0..1)`: ordered-dither transparency (blink, ghost).
- `Sprites.setTint(view, r, g, b, amount)`: mix toward a colour.
- `Sprites.setVisible(view, bool)`: show or hide.
- `Sprites.setMaterial(view, material, opts?)`: swap the sheet; with `opts` also change frame size and grid (the quad is rebuilt).
- `Sprites.snapTo(view, worldX, worldY)`: offset the picture so it lands on the 1/16 pixel grid for a host at that position (no-op when `snap` is off).
- `Sprites.alive(view)`, `Sprites.detach(view)`.
- `Sprites.quad(w, h, pivotX?, pivotY?)`: the cached quad mesh used for sprites and parallax bands.
```luau
local Sprites = require("pixelSprites.sprites")
local mat = asset.resolve("twoDKit.art.fx.fx", "material")
local v = Sprites.attach(e.id, { material = mat, frameWidth = 16, frameHeight = 16, columns = 8, rows = 8 })
Sprites.setCell(v, 0, 5) -- first frame of the gem row
Sprites.snapTo(v, e.position.x, e.position.y)
Sprites.detach(v)
```
For an animated, network-synced sprite with named animations use `pixelSprites.SpriteSheet` (or twoDKit's `Sprite2D` for the kit's characters).
# juice
twoDKit's game feel in one place. Every moment a player has comes through `Juice.moment`: it plays that moment's pixel effect and 8-bit sound on this peer, shakes the camera and holds a short hit stop for this peer's own player, and fires the moment on `twoDKit.events`.
`twoDKit.Sprite2D` calls it from the animation changes it draws (jump, wall jump, land, dash, death) and `twoDKit.Player2D` from its synced fields and Trapline's events (gem, goal, checkpoint, game over, restart). Both run on every peer, so every player sees and hears every other player's moments (others' sounds quieter, fading with distance) with no network traffic of their own.
| Moment | Effect | Sound | Own player only |
|---|---|---|---|
| jump | take-off dust, stretch | `jump` | |
| wallJump | wall-kick dust, stretch | `wallJump` | |
| land | landing dust and squash; a hard landing (a fall of `HARD_LAND_DROP` = 5 tiles or more) throws a wide cloud and squashes harder | `land` / `landHard` | small shake on a hard landing |
| dash | dash ring, speed lines, flashing after-images, stretch along the dash | `dash` | tiny shake |
| gem | crystal pop burst | `gem` | |
| checkpoint | gold star fountain at the flag | `checkpoint` | |
| death | white flash on the sprite, pixel burst at the body | `death` | camera shake, ~75 ms hit stop |
| goal | star fountain | `levelClear` | shake |
| gameOver / restart | | `gameOver` / `click` | sound only for your own |
Sprite2D also kicks up dust when you start running or turn, and scrapes specks off the wall while you wall slide.
## API
- `Juice.moment(name, payload) -> payload`: play a moment and fire it. `payload`: `player`, `x`, `y` (feet), `isLocal`, `face` (1 / -1), plus the moment's own fields.
- `Juice.squash(kind, t, strength?) -> dw, dh`: squash and stretch in whole, even art pixels at `t` seconds into `jump`, `land`, `hardLand`, `wallJump`, `dash` or `dashUp` (`Juice.SQUASH` holds the shapes). Sprite2D draws it with `Sprites.setSquash`, which resamples the frame at art-pixel resolution, so it stays crisp.
- `Juice.landing(drop) -> kind, strength`: "land" or "hardLand" for a fall of `drop` tiles.
- `Juice.shakeCamera(amount)`, `Juice.freeze(seconds)`: this peer's camera shake (tiles) and hit stop (the engine's time scale, held briefly on this peer only).
- Settings on this peer: `Juice.enabled`, `Juice.shake` (multiplier), `Juice.hitstop` (seconds), `Juice.HARD_LAND_DROP`. Per sprite: `Sprite2D.effects`, `Sprite2D.squash`. Sounds: `Player2D.sfxVolume`, `Player2D.sound`, or `twoDKit.sfx`.
```luau
local Juice = require("twoDKit.juice")
Juice.shake = 0.5 -- gentler screen shake
Juice.hitstop = 0 -- no freeze on death
```
# parallax
Parallax scrolling backgrounds for 2D games: a stack of picture bands behind the level, each moving at its own fraction of the camera's motion, so far mountains barely move while near hills sweep past.
Each band is one quad that rides with the camera and is resized to cover the view; the picture scrolls inside it (via the `pixelParallax.parallax` shader; the scrolling itself is the `pixelParallax` package, this module adds creating a background by catalog id) at the band's `factor` horizontally (0 = infinitely far, 1 = moves with the level) and its `yFactor` vertically. Bands are temporary entities each peer draws for itself; nothing is synced. `twoDKit.Level2D` creates, updates and hides one per level; use this module directly for a background outside a Level2D.
## API
- `Parallax.create(backgroundId, opts?) -> Parallax`: spawn the bands of a `twoDKit.catalog` background (`grassland`, `cave`, `castle`, `lab`, `snow`, `desert`, or one you registered; an unknown id falls back to grassland). `opts.baseY` is the world height the pictures' bottom edge rests on (default 0), `opts.depth` the z of the farthest band (default -30; nearer bands step toward z = -2), `opts.parent` an entity to parent the root under.
- `Parallax.update(p, view)`: move and rescroll every band for a view `{ x, y, halfW, halfH }` (pass `twoDKit.view`'s `current()`). Does nothing when the view has not changed.
- `Parallax.setVisible(p, visible)`: show or hide all bands.
- `Parallax.destroy(p)`: despawn them.
- `IMAGE_W`, `IMAGE_H`: one background picture in world units (320 x 180 art pixels = 20 x 11.25 tiles).
```luau
local Parallax = require("twoDKit.parallax")
local View = require("twoDKit.view")
local bg = Parallax.create("snow", { baseY = 0 })
-- every frame, after the camera moved:
Parallax.update(bg, View.current())
-- when done:
Parallax.destroy(bg)
```
Every band is created with the shader's stretch flag on, so a band's top and bottom rows extend past its picture.
# fx
Short-lived pixel-art effects for the twoDKit: jump dust, landing bursts, wall-kick dust, dash rings and sparkles from the kit's `fx` sheet; the bigger moments (death burst, gem pop, checkpoint star fountain, run-start dust, wall-slide specks, hard-landing cloud, dash speed lines) from the `juice` sheet; and flashing, tinted dash after-images ("ghost trail") of any sprite frame.
Each effect is a temporary entity this peer spawns and despawns itself, so effects cost no network traffic: `twoDKit.juice` plays them for the moments `twoDKit.Sprite2D` and `twoDKit.Player2D` see on every peer, and Level2D plays sparkles when a gem is taken or a checkpoint is reached. Effects only play in play mode, and at most 48 run at once.
## API
- `Fx.puff(kind, x, y, facing?)`: play one row of the `fx` sheet (16 x 16) once at a world point, mirrored when `facing < 0`. Kinds (`Fx.ROWS`): `dust`, `land`, `sparkle`, `ring`, `kick`, and the looping-pickup rows `gem`, `goal`, `heart`. An unknown kind does nothing.
- `Fx.burst(kind, x, y, facing?)`: play one row of the `juice` sheet (32 x 32) once. Kinds (`Fx.BURSTS`): `burst` (death), `pop` (gem), `flag` (checkpoint, goal), `streak` (dash) and `slide` centred on the point; `runPuff` and `hardLand` with their bottom at the point (feet).
- `Fx.ghost(material, character, row, col, flipped, x, y, { r, g, b })`: leave a copy of one sprite-sheet cell at (x, y), flashed and tinted toward the colour, then stepping out in four dither stages over 0.3 s, so a trail reads as distinct after-images. `character` is a `twoDKit.catalog` character entry (its frame size and grid).
- `Fx.ROWS[kind]`, `Fx.BURSTS[kind]` = `{ row, frames, fps[, pivotY] }`: the sheet layouts.
- `Fx.enabled`: set false to switch every effect off on this peer.
```luau
local Fx = require("twoDKit.fx")
Fx.puff("land", x, y, 1)
Fx.burst("pop", gemX, gemY + 0.5)
```
The sheets are `twoDKit.art.fx.fx` (painted by `twoDKit.artgen.fx`) and `twoDKit.art.fx.juice` (painted by `twoDKit.artgen.juicefx`), drawn with `twoDKit.sprites`.
# motor
The 2D platformer movement itself as a pure, testable step function: running with acceleration and turn-around, variable-height jump with apex hang, coyote time, jump buffer, wall slide and wall jump, an 8-way dash, ceiling-corner and ledge-lip corner correction, dropping through one-way platforms and riding moving ground. It touches no entities: you hand it a state, a movement feel (`twoDKit.feels`), this step's input and a collision "world", and it moves the state.
Use it to drive a character with your own collision, or to test level layouts and feels headlessly against a level grid with `Motor.gridWorld`. It mirrors the motor inside `twoDKit.Player2D`, which runs the same rules against the engine's physics.
## API
- `Motor.new(x, y, halfWidth, halfHeight) -> State`: a body standing with its feet at (x, y); the box is centred at (x, y + halfHeight).
- `Motor.reset(st, x, y)`: put it at rest at a new point.
- `Motor.step(st, feel, input, dt, world, opts?)`: one fixed step. `input = { x, y, jumpHeld, jumpPressed, dashPressed, down }` (x, y in -1..1; pass `jumpPressed` / `dashPressed` only on the step the button went down). `opts.canDash` / `opts.canWallJump = false` turn those moves off. `opts.airJumps` (default 0) allows that many jumps in mid-air, refilled on the ground and on a wall like the dash: a buffered jump in the air that is neither a coyote jump nor a wall jump spends one, resets the vertical speed to a jump of `feel.airJumpHeight or feel.jumpHeight * 0.85` tiles and adds `"airJump"`. `opts.canSlam` (default false) turns a fresh press of `input.down` in the air (not while dashing) into a slam: `vx = 0`, `vy = -(feel.slamSpeed or 30)`, no gravity or steering until grounded; it adds `"slam"`, then `"slamLand"` on the ground with `st.slamGround = st.groundId` and `st.slamAt = st.clock`. Down + jump on a one-way platform is still a drop (that starts grounded).
- `Motor.anim(st, moveX, canWallJump?) -> (anim, facing)`: the animation to show: idle, run, jump, fall (also while slamming), wallSlide, dash or land, and the facing (wall slides face the wall's side).
- `Motor.move(st, world, axis, d)`, `Motor.probe(st, world, dx, dy, dist)`: the collision helpers the step uses.
- `Motor.gridWorld(grid, ox?, oy?)`: a world over a `twoDKit.level` grid (solid and one-way cells) placed at (ox, oy).
- `Motor.jumpVelocity(height, gravity)`, `Motor.SKIN`.
State fields include `x, y, vx, vy, grounded, groundId, wallDir, coyote, buffer, dashes, dashTimer, facing, airJumpsLeft, slamming, slamGround, slamAt`. Each step appends what happened to `st.events` (`"jump"`, `"airJump"`, `"walljump"`, `"dash"`, `"drop"`, `"slam"`, `"slamLand"`, `"land"`); clear it when you have read it.
## The world
A table answering collision for the state's box:
- `world.cast(st, hx, hy, dx, dy, dist) -> hit?`: sweep a box of half size (hx, hy) along (dx, dy); `hit = { distance, id?, oneWay?, normalY?, surfaceVX? }`.
- `world.groundPos(id) -> (x, y)?`: optional: where a ground entity is now (moving platforms carry the body).
- `world.dropThrough(st, id)`: optional: called when the body starts dropping through a one-way platform.
```luau
local Motor = require("twoDKit.motor")
local Feels = require("twoDKit.feels")
local Level = require("twoDKit.level")
local grid = Level.parse("......\n......\n######")
local world = Motor.gridWorld(grid)
local st = Motor.new(1.5, 1, 0.3125, 0.625)
local feel = Feels.get("tight")
Motor.step(st, feel, { x = 0, y = 0, jumpHeld = true, jumpPressed = true, dashPressed = false, down = false }, 1 / 60, world)
for _ = 1, 30 do
Motor.step(st, feel, { x = 1, y = 0, jumpHeld = true, jumpPressed = false, dashPressed = false, down = false }, 1 / 60, world)
end
print(st.x, st.y, table.concat(st.events, ","))
```
# artgen/juicefx
Paints twoDKit's `juice` effect sheet, `art/fx/juice` (256 x 224, 32 x 32 frames, 8 columns), with `twoDKit.paint`: the death burst, the gem pop, the checkpoint star fountain, run-start dust, wall-slide specks, the hard-landing cloud and dash speed lines that `twoDKit.juice` plays. The older `fx` sheet keeps its rows as they are.
- `rows`: the layout, `{ row, frames, fps, pivotY }` per effect (pivotY 0 = anchored at the feet, 0.5 = centred).
- `paint() -> canvas`, `generate() -> path` (writes the texture and its sprite material).
```luau
require("twoDKit.artgen.juicefx").generate()
```
# backgrounds
Paints the twoDKit's fourteen parallax backgrounds and saves them as art assets. Each background is four 320x180 layers: `sky`, `far`, `mid` and `near`. Each one is a repeating, nearest-filtered texture with a `parallax`-shader material. Run it again whenever the art code changes. It writes to `art/backgrounds/`.
```luau
local Backgrounds = require("twoDKit.artgen.backgrounds")
Backgrounds.generate() -- all fourteen
Backgrounds.generate("castle") -- one
local layers = Backgrounds.paint("snow") -- { sky, far, mid, near } canvases, not saved
print(Backgrounds.info.snow.skyTop) -- "#070b1f"
```
## Exports
- `ids`: `grassland`, `cave`, `castle`, `lab`, `snow`, `desert`, `volcano`, `jungle`, `coast`, `crypt`, `sky`, `factory`, `candy`, `autumn`.
- `info[id] = { skyTop, skyBottom }`: hex colours of the sky layer's top and bottom rows. Use them for a clear colour or to fill above and below the band.
- `generate(id?)` paints and saves textures `<id>_<layer>` (identity `twoDKit.art.backgrounds.<id>_<layer>`) and same-named materials. It returns the texture paths.
- `paint(id)` returns the four canvases without saving them, for previews.
## Layer rules
- `sky` is fully opaque. Its top row is one flat colour, so the parallax shader's stretch mode extends it cleanly.
- `far`, `mid` and `near` use cut-out alpha: every pixel is either alpha 0 or alpha 255. Their content sits in the lower ~55%, ~45% and ~35% of the image. Their bottom row is solid, so stacked layers leave no holes.
- Every layer tiles seamlessly: column 319 continues into column 0. Shapes are drawn through wrapping helpers, and the noise used is periodic.
- Layers get darker, more saturated and more detailed toward the camera. Far layers are hazed toward the horizon colour. Values stay below where the matching tile sets sit, so the level reads in front.
## The fourteen scenes
- **grassland**: afternoon sky with sun and cumulus clouds, snow-capped blue ranges, rolling green hills with copses, and a dark forest edge.
- **cave**: a dark cavern ceiling with stalactites, glowing hanging roots and distant columns, then crystal-lit stalagmites, mossy rock pillars, and foreground rock with big cyan and magenta crystals.
- **castle**: dusk gradient with a crescent moon, stars, a setting sun and lit cloud streaks, a distant fortress on a crag, a crenellated curtain wall with banners and pennants, and a torch-lit parapet.
- **lab**: a dark facility wall with a giant reactor ring, light cones and cyan column strips, then machinery silhouettes, server racks, monitors and pipe runs, and foreground pipes, valves and hazard-striped consoles.
- **snow**: night sky with aurora curtains, moon and stars, moonlit snowy peaks, snowy hills with small pines, and a pine forest on a snowbank.
- **desert**: hot sunset with a banded sun disc, birds and cloud streaks, hazy mesas, striated buttes, and dark rim-lit dunes with saguaro cacti.
- **volcano**: an ember sky under ash clouds lit from below, an erupting cone with lava rivulets and a plume, basalt column clusters standing in a glowing lava river, and black jagged rock with glowing fissures and sparks.
- **jungle**: green mist with slanting sun shafts and a misty canopy, a stepped temple rising out of a hazy forest, tall rainforest trees hung with lianas and vines, and dark undergrowth with big fern fronds.
- **coast**: a bright tropical sky with sun and cumulus, a turquoise sea to the horizon with sparkles, a far island and a sail, rose coral sea stacks with palms in a shallow lagoon, and a sandy beach with big palms and dune grass.
- **crypt**: a violet night with a full moon, cloud streaks and bats, a haunted manor and chapel on a hill with lit windows, gnarled dead trees and graves in rising fog, and an iron cemetery fence with tombstones in ground fog.
- **sky**: a sunrise gradient with a low sun, glowing cloud streaks and pink cumulus, hazy floating islands over a distant cloud sea, big grassy floating islands with trees, hanging roots, waterfalls and a marble ruin, and a sunlit sea of clouds up close.
- **factory**: a smog-orange dusk with a dim sun behind smog bands, a skyline of smokestacks, sheds and cooling towers trailing smoke, a sawtooth-roofed works with lit windows, banded chimneys, a gas holder and a gantry, and a chain-link fence with storage tanks and a pipe run.
- **candy**: a pastel sky with a rainbow, sparkles and cotton-candy clouds, chocolate peaks under pink icing, mint gumdrop hills sprinkled with dots under lollipop trees, and frosted cake ground with drips, giant candy canes and gumdrops.
- **autumn**: a dusk sky with a harvest moon, stars, a flight of geese and cloud streaks, misty hills crowned with woods and a farm with a lit window, a blazing canopy of orange, red and gold trees, and bare twisted trees, a split-rail fence, leaf litter and falling leaves.
# catalog
The style registry of the twoDKit: every character, tile set, parallax background, theme and camera style it ships, as labelled data, plus the `register*` functions your own sprite sheets and tile sets join it through. One field switches each style live:
| Style | Shipped ids | Chosen by |
|---|---|---|
| character | knight, robot, fox, mage | `Player2D.character` / `Sprite2D.character` |
| tile set | grassland, cave, castle, lab, snow, desert | `Level2D.tileset` |
| background | grassland, cave, castle, lab, snow, desert | `Level2D.background` |
| theme (tile set + background) | the ten above | `Level2D.theme` |
| camera | pixelPerfect, smooth, rooms | `Camera2D.style` |
Movement feels live in `twoDKit.feels`. The HUD's style gallery cycles through these lists.
## Character sheets
A character is a sprite sheet (default 8 x 8 grid of 32 x 32 frames, facing right) with named animations `{ row, frames, fps, loop?, col? }` (`col` is the frame a loop restarts from), a collision box in art pixels (`bodyWidth`, `bodyHeight`, default 10 x 20) and an `accent` colour used for the dash after-image. The shipped standard rows are idle, run, jump, fall, wallSlide, dash, land, hurt (rows 0..7). A missing animation falls back along `animFallback` (wallSlide -> fall -> jump -> idle, dash -> run -> idle, land -> idle, hurt -> fall), so a sheet with only idle and run still works.
## API
- Lookups (unknown ids fall back to knight / grassland): `character(id)`, `tileset(id)`, `background(id)`; tables `characters`, `tilesets`, `backgrounds`, `themes`, `cameras` and lists `characterList`, `tilesetList`, `backgroundList`, `themeList`, `cameraList`.
- `anim(character, name) -> (Anim?, resolvedName)`: the animation after fallbacks.
- `registerCharacter(id, t)`: `material` (a material on the kit's sprite shader, or a function returning one), `frameWidth`, `frameHeight`, `columns`, `rows`, `anims`, `bodyWidth`, `bodyHeight`, `accent`, `label`, `description`.
- `registerTileset(id, t)`: `material` (an atlas in the `twoDKit.autotile` layout), `tile`, `decorChance`, `accent`, `label`, `description`.
- `registerBackground(id, t)`: `layers = { { material, factor, yFactor?, stretch? } }` far first (materials on the kit's parallax shader), `skyTop`, `skyBottom`.
- `registerTheme(id, tileset, background, label?)`.
- `resolveStyle(theme, tileset, background) -> (tilesetId, backgroundId)`: `"auto"` or `""` follows the theme.
- `fx()`, `checkpoint()`: the effect and checkpoint flag materials; `hexColor("#rrggbb")` -> `{ r, g, b }` 0..1; `PIXELS_PER_UNIT` (16).
- Gem and checkpoint looks (`Level2D.gemLook`, `Level2D.checkpointStyle`): lists `gemLookList` (crystal, coin, star, cherry, orb, battery) and `checkpointLookList` (flag, lantern, campfire, banner, beacon), tables `gemLooks` / `checkpointLooks` (label, description, sheet row and frame counts), names in `gemLookLabels` / `checkpointLookLabels`, lookups `gemLook(id)` / `checkpointLook(id)` (unknown ids fall back to crystal / flag; Trapline's old look names map to the nearest), sheet materials `gemSheet()` / `checkpointSheet()`, painted by `twoDKit.artgen.pickups`.
```luau
local Catalog = require("twoDKit.catalog")
Catalog.registerCharacter("ninja", {
material = asset.resolve("myArt.ninja", "material"),
frameWidth = 32, frameHeight = 32, columns = 8, rows = 8,
anims = { idle = { row = 0, frames = 4, fps = 6, loop = true }, run = { row = 1, frames = 6, fps = 12, loop = true } },
})
body.component.get("twoDKit.Player2D"):setCharacter("ninja")
```
Registrations live in this peer's module state: run them on every peer (from a module or component every peer loads) so everyone can draw the new style.
# sfx
Synthesised 8-bit sound effects for platformers and arcade games: jump, land, hard landing, dash, wall jump, gem, checkpoint, death, game over, level clear and UI click. Each sound is built from square (with duty cycle), stepped triangle and 15-bit LFSR noise voices with pitch sweeps, vibrato and a chip-style stepped envelope, baked once into a soundClip under `chipSfx.sounds` and shipped with the package. `chipSfx.bake` regenerates them from `Sfx.PRESETS`.
twoDKit plays them itself (through `twoDKit.juice`) on every peer for the moments that peer sees: your own at full volume, other players' quieter and fading out with distance. Nothing goes over the network.
## API
- `Sfx.play(name, opts?) -> boolean`: play one sound on this peer. `opts`: `isLocal` (false for someone else's moment), `x`, `y`, `listenerX`, `listenerY` (distance fade), `volume`, `pitch` (a small random pitch jitter is the default). Each sound has a short cooldown so a burst never stacks.
- `Sfx.volume` (default 0.55) and `Sfx.setVolume(v)`, `Sfx.muted` and `Sfx.setMuted(b)`: this peer's master volume and mute. twoDKit's `Player2D.sfxVolume` sets it too.
- `Sfx.remoteVolume` (0.45) and `Sfx.hearing` (18 tiles): how loud other players are, and how far away they fade out.
- `Sfx.render(nameOrPreset) -> { number }`: the mono samples at `Sfx.RATE` (22050 Hz), for your own sounds, e.g. `Sfx.render({ voices = { { wave = "square", duty = 0.25, dur = 0.1, f0 = 300, f1 = 900, decay = true } } })`.
- `Sfx.PRESETS`, `Sfx.NAMES`, `Sfx.duration(name)`, `Sfx.peak(pcm)`, `Sfx.note(midi)`, `Sfx.clipId(name)`.
```luau
local Sfx = require("chipSfx.sfx")
Sfx.setVolume(0.3)
Sfx.play("click")
```
# api
The front door of the twoDKit: turn a scene into a playable multiplayer 2D platformer in three calls from its `build.luau`: place a level typed as text, write the player template (body, sprite, controller, pixel-perfect camera, spawn point), and add the HUD. It also re-exports the kit's registries so one `require` reaches everything.
```luau
local PP = require("twoDKit.api")
function content()
PP.level({ theme = "grassland", text = [[
##############################
#............................#
#..P.....o.....====.......G..#
####..^^..####......M....#####
]] })
PP.player({ character = "fox", feel = "tight", lives = 3 })
PP.hud()
end
```
## Building a scene
- `PP.level(opts) -> entity`: spawns a `Level2D` entity (named `opts.name`, default "Level") with its bottom-left corner at `opts.position` (default the origin). Passes on `text`, `theme` (default grassland), `tileset`, `background`, `camera`, `seed`, `decorations`, `moverLength`, `moverTravel`, `moverSpeed`, `killDepth`, `roomWidth`, `roomHeight`.
- `PP.player(opts?) -> { prototype, body, rig, spawn }`: writes the scene's player template so every person who joins gets their own: a `PlayerPrototype` with a `body` carrying `Sprite2D` + `Player2D` (`character`, default knight; `feel`, default tight), an owner-only `CameraRig` with an orthographic `Camera` driven by `Camera2D` (`camera` style, default pixelPerfect; optional `targetHeight`), and a `PlayerSpawn` at `opts.position` or the `P` of the last `PP.level`. With `lives > 0` it also adds a `Trapline.Course` (lives, respawn at checkpoints).
- `PP.hud(opts?) -> entity`: adds `Hud2D` (`showStyles`, default true; `title`).
- `PP.startOf(text, ox?, oy?) -> { x, y, z }`: world position (feet) of the `P` in level text placed at (ox, oy), or 2 tiles in from the corner.
## In play (this peer)
- `PP.localPlayer()`: the body this peer controls, or nil until it spawns.
- `PP.setTheme(id)`: switch every level to a theme (tile set + background).
- `PP.setCharacter(id)`, `PP.setFeel(id)`: change this peer's player (synced to everyone).
- `PP.setCamera(style)`: pixelPerfect, smooth or rooms on this peer's camera.
## Re-exports
`PP.Catalog`, `PP.Feels`, `PP.Level`, `PP.Levels`, and `PP.registerCharacter`, `PP.registerTileset`, `PP.registerBackground`, `PP.registerTheme`, `PP.registerFeel` (see `twoDKit.catalog` and `twoDKit.feels`).
# traps
The hazards and power-ups a twoDKit level gets from its text, beyond spikes (`^`) and gems (`o`). `Level2D` builds and animates them on every peer from the same text; `Player2D` asks it whether its body was hit by a hazard (the kill goes through Trapline exactly as spikes do, so lives, checkpoints, respawn and the HUD keep working) and which power-ups it touched.
| char | kind | what it does |
|---|---|---|
| `W` | saw | a spinning 2-tile buzzsaw centred on its cell; costs a life within `SAW_RADIUS` (0.78 tiles) of its centre |
| `L` | lava | an animated pool; the top cell of a column rolls and bubbles. Costs a life below `LAVA_DEPTH` (0.6) of a top cell, anywhere in a cell under lava |
| `X` | crumble | collides like ground; shakes when a player stands on it, falls away after `CRUMBLE.shake` (0.5 s), comes back after `CRUMBLE.gone` (3 s) once nobody is in its cell |
| `F` | jet | a steel block that throws a flame up to `JET.reach` (3) tiles away from the solid it is mounted on (up when the cell above is free, else down, right, left). On the shared Trapline clock: cold, then a warning sputter, then fire (`JET.period` 3 s, `warn` 1.4, `on` 1.9). Costs a life in the flame |
| `H` | heart | restores one Trapline life when lives are on and not full; taken once per run (like a gem). Grey and skipped while lives are full or off |
| `D` | crystal | refills the dash (Celeste style) when it is not full; grows back after `CRYSTAL_RESPAWN` (1 s) |
| `T` | spring | bounces the player `SPRING_HEIGHT` (6.5) tiles up and refills the dash |
## Multiplayer
Nothing here is synced. Every peer builds the same traps from the same text, and fire jets and saws run on Trapline's shared clock (`TL.now`), so they are in step everywhere. Crumbling blocks watch every player body's feet on each peer (the owner's own and the replicated others), so a block breaks for everyone when anyone stands on it. Power-ups are each player's own, as gems are: a heart one player took is still there for the others, and a crystal regrows per player. `Player2D` writes a synced `boost` field when its body takes one, so every peer plays the moment (effect and sound) and the spring's bounce.
## API
- `index(grid)`: the level's traps by kind, cached per grid; jets carry `dir` and `cells`.
- `jetDir(grid, x, y)`, `jetCells(grid, x, y)`, `jetState(t)` -> "off" | "warn" | "on".
- `lavaTop(grid, x, y)`, `hazardIn(grid, x0, y0, x1, y1, t)` (level-local box) and `hazardHit(x0, y0, x1, y1, t?)` (world box, every running level): the hazard's label ("Saw blade", "Lava", "Fire jet") or nil.
- `crumbleStep(state, stood, blocked, dt)`: the crumbling block's state machine; returns "shake", "break", "restore" or nil.
- `spring(st, feel)`, `refillDash(st, feel)`: what a spring and a crystal do to a `twoDKit.motor` state.
- `touch(st, body, feel, collected)`: the power-ups a body touches now, applied; returns `{ kind, level, index, x, y }` for each.
- `build(levelId, parent, grid)`, `animate(levelId, dt, ctx)`, `destroy(levelId)`: what `Level2D` calls.
- `clock()`: the shared clock the hazards run on.
Art: `twoDKit.artgen.hazards` paints `art/fx/hazards`, `art/fx/buzzsaw` and `art/fx/powerups` (rows in `Traps.ROWS`).
# levels
The per-peer registry of the twoDKit's running pieces: every `Level2D` level, every `Player2D` body and every `Camera2D`, and the questions they ask each other: which level is at this point, what are its bounds, did this box touch spikes, where is the start, which body is mine. Players use it for spikes and gem pickups, cameras for clamping to the level and the rooms grid, the HUD for gem totals and level travel.
Each Level2D registers when it builds and unregisters when it rebuilds or goes away; players and cameras add themselves on `awake`. Nothing is synced: every peer builds the same level from the same text.
## API
- `register(entry)`, `unregister(id)`, `get(id)`: level entries `{ id, grid, ox, oy, oz, tileset, background, theme, gems, camera }`; `grid` is a `twoDKit.level` grid and `(ox, oy)` the world position of its bottom-left corner.
- `all()`: every registered level whose entity still exists, in registration order.
- `bounds(entry) -> x0, y0, x1, y1`: the level's world rectangle.
- `at(x, y)`: the level containing the point, or the nearest one.
- `spikeHit(x0, y0, x1, y1)`: does the world box touch any level's spikes?
- `start(entry) -> x, y`: world position (feet) of the level's `P` start marker, or nil.
- `addPlayer` / `removePlayer`, `players()`: every Player2D body on this peer, sorted.
- `localPlayer()`: the Player2D body this peer controls, or nil.
- `addCamera` / `removeCamera`, `cameras()`.
```luau
local Levels = require("twoDKit.levels")
local me = Levels.localPlayer()
if me then
local lv = Levels.at(me.position.x, me.position.y)
if lv then print("gems in this level:", #lv.gems, "start:", Levels.start(lv)) end
end
```
# view
The shared "what does the 2D camera see right now" record for the twoDKit: the centre of the view, its half width and half height in world units (tiles) and the pixel zoom. `twoDKit.Camera2D` publishes it every frame; parallax backgrounds and anything else that frames or culls by the camera reads it.
When no Camera2D has published in the last quarter second (edit mode, or a different camera is in charge), `current()` falls back to the first camera the engine's `camera.list` tool reports, re-read at most four times a second: its position, and its `orthoHeight` when orthographic (otherwise a view 16 tiles tall), with the width taken from the viewport's aspect.
Everything here is local to this peer; nothing is synced.
## API
- `View.publish(x, y, halfW, halfH, zoom)`: record the view this frame. Camera2D calls it; call it yourself only if you write your own 2D camera.
- `View.current(): State`: the latest view: `{ x, y, halfW, halfH, zoom, frame }` (`frame` is the `os.clock()` time it was taken).
```luau
local View = require("twoDKit.view")
local v = View.current()
local onScreen = math.abs(px - v.x) < v.halfW and math.abs(py - v.y) < v.halfH
```
## In the kit
Written by Camera2D, read by Level2D to drive and show only the parallax background of the level the view is in (see `twoDKit.parallax`).
# pixelParallax.parallax
Background bands for 2D parallax, any number of layers, driven by your own camera code. `create(layers, opts)` spawns one band per layer (`{ material, factor, yFactor?, stretch? }`, far first; `opts` = `baseY`, `depth`, `parent`, `name`), `update(p, { x, y, halfW, halfH, zoom? })` moves and rescrolls them for a view, `setVisible`, `destroy`. `bandUV(view, factor, yFactor, baseY, zoom)` is the pixel-exact mapping (scroll rounded to whole screen pixels). `IMAGE_W` / `IMAGE_H` = 20 x 11.25 world units per picture. Used by `pixelParallax.ParallaxBackground` and `twoDKit.parallax`.
# Level2D
A 2D platformer level painted from text: type rows of characters into `text` and it becomes a playable tilemap: autotiled ground with the right edge and corner tile in every cell, merged seamless collision, one-way platforms, spikes, scattered decorations, Trapline checkpoints with pixel flags, platformsKit moving platforms drawn as tile-set planks, spinning gems, a goal, the player start, a kill zone below, and a parallax background behind it.
Put it on any scene entity; the entity's position is the bottom-left corner of the grid and one character is one world unit (16 art pixels). Several Level2D entities can sit side by side in one scene. Players (`twoDKit.Player2D`), the camera (`twoDKit.Camera2D`) and the HUD find it through `twoDKit.levels`. Checkpoints and the kill zone need the `Trapline` package, moving platforms the `platformsKit` package; without them those pieces are skipped.
```luau
local lvl = entity.spawn("CaveLevel")
lvl.position = { 0, 0, 0 }
lvl.component.add("twoDKit.Level2D", { theme = "cave", camera = "smooth", text = [[
##############################
#............................#
#..P.......o......=====...G..#
#.........###.............####
#....C..^^###....M.....^^#####
##############....############
]] })
```
## Legend
`#` ground, `=` one-way platform, `^` spikes (point away from the solid beside them), `B` back wall (drawn behind, no collision), `P` (or `S`) player start, `C` checkpoint, `M` moving platform side to side, `V` moving platform up and down, `o` gem, `G` goal, `*` forced decoration, `.` or space empty. Unknown characters count as empty and are warned about (see `problems()`). Full format: `twoDKit.level`.
## Fields (local, not synced)
| Field | Default | What |
|---|---|---|
| `text` | `""` | The level, top row first. Changing it rebuilds everything. |
| `theme` | `"grassland"` | grassland, cave, castle, lab, snow or desert: tile set and background together. |
| `tileset` | `"auto"` | Tile set override (`auto` follows the theme). |
| `background` | `"auto"` | Background override (`auto` follows the theme, `none` = no background). |
| `camera` | `""` | Camera style this level asks Camera2D for: pixelPerfect, smooth, rooms (`""` = the camera's own). |
| `seed` | `1` | Where decorations grow. |
| `decorations` | `true` | Scatter the tile set's decorations on free floor tiles. |
| `killDepth` | `3` | Trapline kill zone this many tiles below the bottom row (0 = none). |
| `checkpointStyle` | `"flag"` | How each `C` looks: `flag`, `lantern`, `campfire`, `banner` (totem banner) or `beacon` (sci-fi), each with an idle and a reached animation (`Catalog.checkpointLookList`). Old Trapline look names map to the nearest one. |
| `gemLook` | `"crystal"` | How each `o` looks: `crystal`, `coin`, `star`, `cherry`, `orb` (soul flame) or `battery` (power cell), each animated with its own collect burst (`Catalog.gemLookList`). |
| `moverLength` / `moverTravel` / `moverSpeed` | `4` / `5` / `2` | Width and travel in tiles, and speed in tiles/s, of `M` / `V` platforms. |
| `roomWidth` / `roomHeight` | `20` / `12` | Room size in tiles for the `rooms` camera. |
| `edgeWalls` | `true` | Invisible walls just past the left and right edges. `false` joins rooms: place two Level2Ds side by side (the second at the first's x + width) with a gap in their touching edge columns and a player walks from one into the other; stack them (the lower one's top at the upper one's bottom) with a gap in the floor and ceiling rows to fall and jump between them (use `killDepth = 0` on the upper room). With it off the kill zone spans only the level's own width. Camera2D clamps to whichever level the player is in, and only that level draws its background. |
Changing `theme`, `tileset`, `background`, `decorations`, `seed`, `gemLook` or `checkpointStyle` rebuilds only the pictures, live; collision, checkpoints and platforms stay as they are.
## Methods
- `problems()`: problems found the last time the text was read.
- `size()`: width and height in tiles.
- `startPosition()`: world position `{ x, y, z }` (feet) of the `P` marker, or a point 2 tiles in from the bottom-left corner when there is none.
- `setTheme(id)`: set `theme` and put `tileset` and `background` back to `auto`.
## How it works
Every peer builds the same level from the same text on temporary child entities, so nothing about the level crosses the network and nothing it spawns is saved. Solid cells merge into as few `BoxCollider` rectangles as possible (no seams to catch on), one-way runs become thin one-way colliders at the top of their cells, and tall walls close the left and right edges. Only the level the view is in draws its background. Gem pickups are per player: a gem bursts and disappears for a player once that player's Player2D has taken it. Each `C` is a `Trapline.Checkpoint` with look `none`: Trapline handles touching it and coming back at it and builds and animates nothing, so a checkpoint costs next to nothing per frame; the kit draws the pixel checkpoint from `art/fx/checkpoints` and gems from `art/fx/gems` (painted by `twoDKit.artgen.pickups`).
# autotile
The tile atlas layout every twoDKit tile set shares, and 47-tile "blob" autotiling: given which of a solid cell's eight neighbours are also solid, it picks the atlas tile with the right edges, outer corners and inner corners. Pure data and maths, no engine calls.
Used by `twoDKit.level` to choose tiles when it builds a level's mesh, and by the tile set generator (`twoDKit.artgen.tilesets`) to paint each cell. Read it when you draw your own tile set atlas so it lines up.
## Atlas layout
8 columns x 8 rows of 16 x 16 pixel cells (a 128 x 128 image), cell index = `row * 8 + column` counted from the top-left.
| Cells | Holds |
|---|---|
| 0..46 | ground, one tile per blob mask: cell `i` is drawn for `Autotile.masks[i + 1]` |
| 47 | back wall (`BACKWALL`), a darker fill drawn behind the level |
| 48..51 | one-way platform: left end, middle, right end, single (`ONEWAY.left/mid/right/single`) |
| 52..55 | spikes pointing up, down, left, right (`SPIKES.up/down/left/right`) |
| 56..63 | eight decorations standing on the floor below them (`DECOR_FIRST`, `DECOR_COUNT`) |
## Neighbour mask
A bit is set when that neighbour is solid ground: `N = 1, NE = 2, E = 4, SE = 8, S = 16, SW = 32, W = 64, NW = 128` (also exported as `Autotile.N` ... `Autotile.NW`). A clear cardinal bit is an exposed edge. A diagonal bit only counts when both cardinals beside it are set; N and E solid with NE empty is an inner-corner notch.
## API
- `TILE` (16), `COLUMNS` (8), `ROWS` (8): atlas geometry.
- `reduce(mask)`: drop every diagonal bit whose two cardinals are not both set (256 masks become 47).
- `masks`: the 47 reduced masks in ascending order.
- `index(mask)`: atlas cell for any of the 256 raw masks.
- `open(mask, bit)`: true when that side is exposed (the neighbour is empty).
- `cellOrigin(index, tile?)`: pixel (x, y) of a cell's top-left corner.
- `cellUv(index)`: `u0, v0, u1, v1` of a cell, v growing downward.
```luau
local Autotile = require("twoDKit.autotile")
local mask = Autotile.N + Autotile.E + Autotile.NE -- ground above and to the right
local cell = Autotile.index(mask)
local u0, v0, u1, v1 = Autotile.cellUv(cell)
```
# feels
Platformer movement feels as plain data: every number the `twoDKit.Player2D` motor runs on (run speed and acceleration, variable jump height, gravity, apex hang time, coyote time, jump buffer, wall slide and wall jump, dash), grouped into named presets. `Player2D.feel` picks one by id; register your own to tune the controls without touching code.
Units are tiles (world units, 16 art pixels) and seconds.
## Presets (`Feels.list`)
- `tight`: snappy and precise (Celeste-like): instant turns, quick fall, short hops on a tap, fast long dash.
- `floaty`: low gravity, long hang at the top of the jump, drifting air control, long slow dash.
- `heavy`: slow to start, short strong jump, slams down, little air control, short punchy dash.
- `slippery`: on ice: high top speed, long slides to stop or turn, momentum carries through jumps.
- `classic`: momentum platforming: builds up to a high top speed, slides a tile when you let go, big steerable jumps.
- `nimble`: an acrobat: two dashes per jump, high wall jumps off slow wall slides, instant and light.
- `moon`: barely any gravity: six-tile jumps lasting almost three seconds, slow drift down, gentle steering.
- `retro`: 8-bit committed jumps: one fixed arc however long you hold, almost no air steering, instant on the ground.
## Fields of a feel
Running: `maxRun`, `groundAccel`, `groundDecel`, `turnAccel`, `airAccel`, `airDecel`, `groundFriction` (multiplies ground deceleration and turning; all presets use 1). Jumping: `jumpHeight` (apex of a held jump), `riseGravity`, `fallGravity`, `cutGravity` (after jump is released: short hop), `apexHang` (gravity multiplier near the apex while held), `apexWindow`, `maxFall`, `coyoteTime`, `jumpBuffer`, `landSquash`. Walls: `wallSlide` (max slide speed), `wallJumpX`, `wallJumpHeight`, `wallJumpLock` (seconds the wall jump overrides steering). Dash: `dashSpeed`, `dashTime`, `dashCount` (dashes per air time), `dashEndScale`, `dashCooldown`, `overspeedDecel` (on the ground, speed above `maxRun` after a dash bleeds off at least this fast). Plus `id`, `label`, `description`.
## API
- `Feels.get(id?) -> Feel`: a preset (unknown or nil gives `tight`).
- `Feels.copy(id) -> Feel`: a shallow copy to edit.
- `Feels.register(id, t) -> Feel`: add or replace a feel; numbers you leave out come from `tight`. It joins `Feels.list`, so the HUD's FEEL picker offers it.
- `Feels.jumpVelocity(height, gravity)`: launch speed that peaks at `height`.
- `Feels.byId`, `Feels.list`.
```luau
local Feels = require("twoDKit.feels")
Feels.register("moon", { label = "Moon", description = "Huge, slow jumps.", jumpHeight = 6, riseGravity = 12, fallGravity = 15 })
body.component.get("twoDKit.Player2D"):setFeel("moon")
```
# characters
Generator for the kit's twelve playable character sprite sheets: `knight`, `robot`, `fox`, `mage`, `ninja` (masked, long red scarf, katana on the back), `astronaut` (bubble helmet with a gold-rimmed visor, life-support pack with a blinking whip antenna, thruster puffs on take-off and dash), `frog` (big eyes on top of a wide head, webbed feet, pink bandana, dizzy eyes and tongue out when hurt), `pirate` (tricorn hat, eyepatch, beard, long coat tails, cutlass), `skeleton` (bone limbs, ribcage, glowing green eye lights, a clacking jaw, tattered cloak, femur club), `viking` (stocky, horned iron helm, braided ginger beard, quartered round shield on the back, bearded axe), `slime` (a limbless pink jelly blob in a gold crown, painted whole by `drawBody`: it squashes, stretches and hops, smears against walls and drips goo) and `bird` (round bluebird with a crest, goggles and a beak, wings drawn by `drawWing` in place of arms so they flap up on jumps). It paints each one in code with `twoDKit.paint` and saves it as a nearest-filtered texture plus a `twoDKit.sprite` material under `twoDKit.package/art/characters/<id>`.
```lua
local Chars = require("twoDKit.artgen.characters")
Chars.generate() -- all twelve
Chars.generate("fox") -- one
local canvas = Chars.sheet("mage") -- paint without saving (previews)
```
Exports: `ids`, `rows` (animation table), `generate(id?)`, `sheet(id)`.
## Sheet format
256x256, an 8x8 grid of 32x32 frames, frame (col, row) at pixel (col*32, row*32) from the top-left. The character faces right, feet on y = 31, body centred on x = 16. The core body is about 12 px wide (x 11..22) and 23 px tall (y 8..31). The plume, hat, antenna, ears, tail, cape and effects reach further. Unused frames are transparent.
| row | anim | frames | fps | loop |
|---|---|---|---|---|
| 0 | idle | 6 | 8 | yes |
| 1 | run | 8 | 14 | yes |
| 2 | jump | 3 | 12 | no, hold last |
| 3 | fall | 3 | 10 | frame 0 once, then loop 1..2 |
| 4 | wallSlide | 3 | 10 | yes; the wall is on the character's RIGHT and the character faces away from it (left) |
| 5 | dash | 4 | 20 | no |
| 6 | land | 3 | 16 | no, then idle |
| 7 | hurt | 2 | 10 | no |
## How it is painted
Each frame is a pose on a small rig: two-bone IK legs and arms are drawn as shaded capsules, and the heads and torsos are hand-authored ASCII sprites. Capes, tails, scarves, plumes, hat tips and antennas are chains pushed by a per-pose "wind" vector and swayed by a travelling wave. Each depth layer (cloth/tail, far limbs, body, head, near arm/held item) gets its own coloured 1 px outline, so limbs separate cleanly. Light comes from the top-left, and far limbs drop one step down their ramp. Dust, sparks, speed streaks, the dash afterimage and hurt stars are drawn last, without an outline. All pixels are fully opaque or fully transparent, which the cutout sprite material needs.
To add a character, add a `CH.<id>` constructor (palette ramps, `drawBack`, `drawTorso`, `drawHead`, and optionally `drawOverLegs`, `drawHeld` and `drawFrontArmPost`), then add the id to `ids`.
# events
A tiny local event bus for twoDKit's game moments: `jump`, `land`, `dash`, `wallJump`, `gem`, `checkpoint`, `death`, `gameOver`, `restart` and `goal`. A HUD, a sound bank, an achievement tracker or your own game code listens to them instead of polling fields.
Moments fire on every peer, for every player that peer sees, from state that is already synced (Sprite2D's animation changes, Player2D's `gems` and `finished`, Trapline's checkpoint, lifeLost, gameOver and restarted events), so listening costs no network traffic. The kit's own effects and sounds (`twoDKit.juice`) are driven the same way.
## API
- `Events.on(name, fn) -> connection`: call `fn(payload)` for every `name` moment (`"*"` hears all of them). `connection:Disconnect()` stops it.
- `Events.once(name, fn) -> connection`: only the next one.
- `Events.emit(name, payload?) -> payload`: fire a moment on this peer (the kit does this; your game may emit its own names too).
- `Events.count(name)`: listeners of a moment.
- `Events.NAMES`: the kit's moment names.
Every payload carries `event`, `player` (the body's entity id), `x` and `y` (its feet, in world units), `face` (1 or -1) and `isLocal` (true when it is this peer's own player). Extra fields: `land` has `hard` and `drop` (tiles fallen); `dash` has `dx`, `dy` (its direction, fired a couple of frames in); `gem` has `count`; `checkpoint` has `first` and `label`; `goal` has `gems` and `time`; `gameOver` has `deaths`. `death` fires as the body goes down (its hurt animation starts).
```luau
local Events = require("twoDKit.events")
Events.on("gem", function(e)
if e.isLocal then print("gems now", e.count) end
end)
```
# pixelSprites: animated pixel-art sprites from any sprite sheet
Draw a character or object as a flat pixel-art picture that plays named animations from a sprite sheet, in any Zero world, with no other kit. It is the sprite layer of [twoDKit](https://origozero.ai) and works on its own.
- **`SpriteSheet` component**: name your animations once as rows of the sheet (`"idle=0:6:8, run=1:8:14, jump=2:3:12:once"`), then switch with one field (`anim`). It faces left or right (`facing`), stays snapped to the art's pixel grid so it never shimmers, and `anim` and `facing` sync, so every player sees every other player's animation.
- **`sprites` module**: attach a picture showing one cell of a sheet to any entity and drive it yourself: `setCell`, `setFlash` (hit flash), `setFade` (dithered fade), `setTint`, `setSquash` (squash and stretch that stays pixel-crisp), `snapTo`.
- **`sprite` shader**: unlit, alpha-cut, nearest-filtered; one material draws every sprite that uses the sheet.
## Install
```lua
tools.use("zeromind", "installAsset", "af866662-98d1-4500-bd67-49508538bb47") -- or `zero zeromind installAsset af866662-98d1-4500-bd67-49508538bb47` in the shell
```
or search ZeroMind for "pixelSprites" / "animated sprite sheet". It lands at `/source/pixelSprites.package`.
## Your first animated sprite
A sheet is a texture with the frames in a grid, top row first, and a material on the `pixelSprites.sprite` shader. Make the material by importing your sheet as a texture (nearest filter) and creating a material whose shader is `pixelSprites.sprite` with that texture as its base colour, or paint one in code with twoDKit's `twoDKit.paint` (`Paint.save` then `Paint.material`). With one in hand:
```lua
function content()
local hero = entity.spawn("Hero", { position = { 0, 1, 0 } }) -- the position is the feet
hero.component.add("pixelSprites.SpriteSheet", {
sheet = asset.resolve("my.art.hero", "material"),
frameWidth = 32, frameHeight = 32, columns = 8, rows = 8,
animations = "idle=0:6:8, run=1:8:14, jump=2:3:12:once, fall=3:3:10",
})
end
```
Then, from your own code: `hero.component.get("pixelSprites.SpriteSheet").anim = "run"` and `.facing = -1` to face left. `:play("jump", true)` restarts an animation, `:isFinished()` says whether a `:once` animation reached its last frame.
## SpriteSheet fields
| Field | Default | What |
|---|---|---|
| `sheet` | none | The material (on the `pixelSprites.sprite` shader). |
| `frameWidth`, `frameHeight` | `32` | One frame in pixels. |
| `columns`, `rows` | `8` | The sheet's grid. |
| `animations` | `idle=0:1:1` | `name=row:frames:fps`, add `:once` to hold the last frame; rows count from the top, starting at 0. |
| `anim` | `idle` | The animation playing (synced). |
| `facing` | `1` | `1` as drawn, `-1` mirrored (synced). |
| `speed` | `1` | Animation speed multiplier. |
| `pixelsPerUnit` | `16` | Art pixels per world unit. |
| `pixelSnap` | `true` | Keep the picture on the art's pixel grid. |
| `z` | `0` | Depth offset. |
## Notes
- The picture is drawn on a temporary child entity on each peer; nothing about it is saved or sent except `anim` and `facing`.
- For crisp pixels on screen use an orthographic camera whose height is the window height divided by a whole number of screen pixels per art pixel (twoDKit's `Camera2D` does this, and `pixelParallax` scrolls backgrounds to match).
- The engine's own flipbook (`animatedTexture`) plays texture layers on a clock; it cannot pick named animations or mirror, which is why this package exists.
## Changelog
- **1.1.0**: a SpriteSheet can take a plain sprite-sheet texture (`texture`) instead of a material; pixelSprites builds the sprite material from it at runtime (`Sprites.sheetMaterial`), so a game ships the texture alone, with no material asset or material preview per sheet. `sheet` works exactly as before.
- **1.0.3**: this changelog. No change to the component, module or shader.
- **1.0.2**: the package description says what it gives you and how to install it.
- **1.0.1**: real install lines in the README, and how to make a sheet material.
- **1.0.0**: first release, split out of twoDKit 1.1.0: the `SpriteSheet` component, the `sprites` module and the `sprite` shader.
# chipSfx: 8-bit sound effects for platformers
Eleven ready-made 8-bit sound effects for any Zero game, made the way an old console sound chip makes them: **jump, land, hard landing, dash, wall jump, gem, checkpoint, death, game over, level clear and a UI click**. Each one is synthesised from square (with duty cycle), stepped triangle and 15-bit noise voices with pitch sweeps, vibrato and a stepped envelope, and shipped as a soundClip, so playing one costs nothing. Play a sound on this peer with one call; another player's sounds come out quieter and fade with distance, and nothing goes over the network.
It is the sound of **twoDKit** (the 2D pixel platformer kit), which installs it.
## Install
`zero zeromind installAsset 08ec245b-eb89-41f3-a761-1e92b71c1bac` in the engine shell, or search ZeroMind for "chipSfx" or "8-bit sound effects". No dependencies.
## Play a sound
```luau
local Sfx = require("chipSfx.sfx")
Sfx.play("jump") -- your own moment, full volume
Sfx.play("gem", { isLocal = false, x = 12, y = 3, -- someone else's: quieter,
listenerX = 4, listenerY = 3 }) -- fading with distance
Sfx.setVolume(0.4) -- this peer's master volume
```
## Make your own sound
Add a preset (voices of `square`, `triangle` or `noise` with a duration, start and end pitch, duty, vibrato and decay), hear its samples with `Sfx.render`, and bake it into a clip with `chipSfx.bake`:
```luau
local Sfx = require("chipSfx.sfx")
local pcm = Sfx.render({ voices = { { wave = "square", duty = 0.25, dur = 0.1, f0 = 300, f1 = 900, decay = true } } })
```
`sfx.module`'s README lists every field and function.
## Changelog
- **1.0.1**: the install line names this package's id.
- **1.0.0**: first release, split out of twoDKit (where it was `twoDKit.sfx` and `twoDKit.artgen.sfx`, which still work).
# pixelParallax: pixel-crisp parallax backgrounds
Backgrounds that scroll behind a 2D scene at different depths, far layers barely moving and near ones sweeping past, in any Zero world, with no other kit. It is the background layer of twoDKit (all its ten themed backgrounds run on it) and works on its own.
- **`ParallaxBackground` component**: up to four layers, `sky`, `far`, `mid` and `near`, each a picture with a factor (how much of the camera's motion it follows: 0 = fixed, 1 = moves with the scene). It follows whichever camera is rendering, or the one you name.
- **`parallax` module**: the same for any number of layers, driven by your own camera code: `create(layers, opts)`, `update(p, view)`, `setVisible`, `destroy`, and `bandUV` (the pixel-exact texture mapping).
- **`parallax` shader**: unlit, alpha-cut, nearest-filtered; repeats each picture sideways.
Scrolling is rounded to whole screen pixels measured from the view's edges, so a background pixel is exactly as big and as still as a tile pixel at any window size. Depends on `pixelSprites` (for the quad), which installs with it.
## Install
```lua
tools.use("zeromind", "installAsset", "81b13a43-8a9b-4a93-a4ca-4c09c5194dbe") -- or `zero zeromind installAsset 81b13a43-8a9b-4a93-a4ca-4c09c5194dbe` in the shell
```
or search ZeroMind for "pixelParallax" / "parallax background".
## Your first background
Each layer picture is 320 x 180 pixels (20 x 11.25 world units at 16 per unit), with transparent sky in the nearer layers, and a material on the `pixelParallax.parallax` shader:
```lua
function content()
local bg = entity.spawn("Background")
bg.component.add("pixelParallax.ParallaxBackground", {
sky = asset.resolve("my.art.sky", "material"), skyFactor = 0,
far = asset.resolve("my.art.mountains", "material"), farFactor = 0.15,
mid = asset.resolve("my.art.hills", "material"), midFactor = 0.35,
near = asset.resolve("my.art.trees", "material"), nearFactor = 0.6,
baseY = 0,
})
end
```
## ParallaxBackground fields
| Field | Default | What |
|---|---|---|
| `sky`, `far`, `mid`, `near` | none | Layer materials, far to near; leave any empty. |
| `skyFactor`, `farFactor`, `midFactor`, `nearFactor` | `0`, `0.15`, `0.35`, `0.6` | Share of the camera's motion each layer follows (vertically half of it). |
| `baseY` | `0` | World height of the pictures' bottom edge when the camera is at height 0. |
| `depth` | `-30` | Depth of the farthest layer; the others stand in front of it. |
| `camera` | empty | The camera to follow; empty = the one the renderer is using. |
| `viewHeight` | `11.25` | View height used when that camera is not orthographic. |
## With your own camera
```lua
local Parallax = require("pixelParallax.parallax")
local p = Parallax.create({ { material = sky, factor = 0 }, { material = hills, factor = 0.3 } }, { baseY = 0 })
-- every frame, after the camera moved (halfW / halfH in world units, zoom = screen pixels per art pixel):
Parallax.update(p, { x = camX, y = camY, halfW = hw, halfH = hh, zoom = zoom })
```
Every peer draws its own background on temporary entities; nothing is synced or saved.
## Changelog
- **1.0.3**: this changelog. No change to the component, module or shader.
- **1.0.2**: the package description says what it gives you and how to install it; the `parallax` shader has a preview picture; built on the engine's library d4061d2.
- **1.0.1**: real install lines in the README.
- **1.0.0**: first release, split out of twoDKit 1.1.0: the `ParallaxBackground` component, the `parallax` module (with `anchorY`, so a level placed above the origin shows its background) and the `parallax` shader.