# defs
The three bosses as data: id, display name, title, default max health, phase count, sheet frame size, body box (half width, half height, centre height above the feet), whether it flies, its sheet material and its sound names; plus the animation rows every sheet shares (`Defs.ANIMS`) and the rows of the fx sheet (`Defs.FX`). Read by the api, moves and Boss2D.
# BossSpawn
Puts one networked pixelBosses boss in a scene, the same one on every peer. Put it on a plain entity in a scene build (not `entity.spawnSynced`): its position is where the boss's feet stand, and its fields say which boss and its arena. It needs no sibling components; the boss it spawns is a separate entity carrying a `pixelBosses.Boss2D`.
```lua
local s = entity.spawn("BossSpawn_lair", { position = { 18, 1, 0 } })
s.component.add("pixelBosses.BossSpawn", { bossName = "Boss_lair", kind = "thornKnight",
arenaMinX = 1, arenaMinY = 1, arenaMaxX = 23, arenaMaxY = 11, maxHealth = 12 })
-- in play, on any peer:
local id = s.component.get("pixelBosses.BossSpawn"):bossId() -- or require("pixelBosses.api").byName("Boss_lair")
```
- **Spawn once**: in play, after the room answers this peer's join and `settle` seconds pass, each peer looks for the boss by `bossName`. If the room already holds it, that is the boss. If not, the lowest peer id in the room spawns it with `entity.spawnSynced` and adds the Boss2D, so its synced state, health and moves reach every peer. A peer further down the order waits `settle + rank * Bosses.SPAWN_STAGGER` seconds before spawning, in case the lowest peer never does. If two ever exist, the owner of each one but the lowest id despawns its own.
- **Late joiners** receive the existing boss from the room. **The owner leaving** hands it to a peer that stays (the engine's ownership handover), with its health kept. **Re-entering play** finds the boss the room still holds, or spawns a fresh one when the room is empty: never a duplicate.
- **Edit mode**: shows and spawns nothing.
- **Why**: a boss spawned with `entity.spawnSynced` inside a scene build reached a peer that entered play second without a replication record, so its fight never synced there.
Fields (all per peer, not synced): `bossName` (empty = this entity's name + `_boss`), `kind`, `arenaMinX`, `arenaMinY`, `arenaMaxX`, `arenaMaxY`, `maxHealth` (0 = the kind's default), `settle`. Methods: `bossId()` (nil until the boss exists on this peer), `boss()` (its Boss2D), `name()`. The decision itself is `pixelBosses.api` `_spawnPlan`, a pure function the tests drive.
# api
The contract other kits use with slash2D: `Slash.addTarget(entityId, { halfW, halfH, offsetX?, offsetY?, onHit })` / `Slash.removeTarget(handle)` to make an entity hittable on this peer, `Slash.on("swing" | "hit", fn)` for events every peer gets, and `Slash.schemeWithAttack(baseName)` to build a controlsKit scheme with an attack button. Called by enemy and prop code and by the Slash2D component.
# moves
Every boss attack as a pure function of time, so every peer computes the same thing from one synced move: `Moves.pose(def, move, t, arena)` (where the boss is and which frame it shows), `Moves.hazards(def, move, t, arena, out)` (projectiles, shockwaves, lasers, fists, missiles and telegraph markers, each with a hurt box and a sprite cell), `Moves.cues(def, move, arena)` (sounds, shakes, hit-stops, explosions, stinger spawns by time) and `Moves.plan(def, ctx)`, the AI the authority runs to pick the next move. Timings live in `Moves.KNIGHT`, `Moves.QUEEN` and `Moves.WARDEN`. Used by Boss2D; handy for tests and for tuning.
# api
The front door of pixelBosses: `Bosses.list()` and `Bosses.info(id)` (display name, title, max health, phases), `Bosses.on("phase" | "defeated" | "hurt" | "state" | "*", fn)` events that fire on every peer, `Bosses.all()` / `Bosses.get(id)` for the Boss2D components on this peer, `Bosses.hitbox(id)` for any attack system, the replaceable `Bosses.hurtPlayer(body, info)` (default: a Trapline life) with its `Bosses.INVULNERABLE` window, and `Bosses.now()`, the shared clock moves are timed on. It also carries damage, activate / reset commands and minion deaths between peers. Called by game code, arena kits and the Boss2D component.
# Boss2D
A 2D side-scrolling pixel-art boss with two phases, for twoDKit platformers: put it on an entity whose position is the boss's start (feet on the arena floor), pick a `kind` (`thornKnight`, `hiveQueen` or `ironWarden`) and give it the arena bounds. It needs no sibling components: it draws its own sprite and effects on temporary child entities, and finds players through twoDKit's player registry.
```lua
local boss = entity.spawnSynced("Boss", { position = { 18, 1, 0 } })
boss.component.add("pixelBosses.Boss2D", { kind = "hiveQueen", arenaMinX = 1, arenaMinY = 1, arenaMaxX = 23, arenaMaxY = 11 })
-- in play, from any peer:
boss.component.get("pixelBosses.Boss2D"):activate()
```
- **States**: `dormant` (waits, cannot be hurt) -> `activate()` -> `intro` (a roar; sword hits already count) -> `fighting` -> `defeated` at 0 health (a death animation with a chain of explosions). `reset()` puts it back at full health, dormant, at its start, with every projectile cleared.
- **Brain**: on the authority an `aiKit.bt` behaviour tree picks what happens each frame (asleep, finished, dying, phase change, waking, busy, next attack); the attacks themselves are `pixelBosses.moves`.
- **Health**: a `SecondWind.pool` record on the authority, mirrored into the synced `health`.
- **Phases**: phase 2 starts at or below half health (`Defs.PHASES`) with a roar, a hit-stop and a burst, and adds the kind's phase-2 attacks.
- **Damage**: `damage(amount, attackerId, dirX)` on any peer; the authority applies it (flash, a small flinch toward `dirX`). With slash2D installed the boss registers itself as a slash target on every peer, at its live body box, and every peer flashes it and plays juiceKit sparks for every counted sword hit (`pixelBosses.feel`).
- **Hurting players**: each peer tests only its own player against the body and every live hazard and calls `pixelBosses.api` `hurtPlayer` (default: a Trapline life), at most once a second.
- **Multiplayer**: spawn the entity with `entity.spawnSynced`; its owner runs the AI and writes each move once into the synced `move` field, and every peer simulates the same moves on the shared clock.
Fields: `kind`, `arenaMinX`, `arenaMinY`, `arenaMaxX`, `arenaMaxY`, `maxHealth` (0 = the kind's default; resolved in play), and read-only synced `health`, `phase`, `state`, `move`, `hitDir`, `resets`; per-peer `contactDamage`, `debugLabel`, `sound`. Methods: `activate`, `reset`, `damage`, `isDefeated`, `hitbox`, `hazards`, `displayName`, `maxHp`. The package README lists every attack per phase.
# pixelBosses: three 2D pixel-art boss fights with phases
Drop a boss into any **twoDKit** platformer or metroidvania and get a full Hollow Knight / Super Metroid style boss fight: a big hand-painted pixel sprite (3 to 5 tiles tall) with idle, move, wind-up, attack, hurt, roar, death and special animations, an intro roar, telegraphed attacks, a second phase at half health, hit flash and flinch, camera shake on slams, hit-stop on the phase change and a big chain of explosions on death, with 8-bit roars, slams, shots, lasers and booms. It is multiplayer by default and costs no network traffic per projectile.
Version **1.2.3** (`Bosses.VERSION`). Install in the engine shell: `zero zeromind installAsset 8b4bbe69-ddf9-4217-9a00-a1fafbcc969d`. A `BossSpawn` in the scene puts one networked boss in play that every player, late joiners included, shares. Every sword hit lands and counts: from either side or from above (down-slash pogo), in both phases, during every attack (charges, leaps, dives, swoops, hops, lasers) and from the moment the boss wakes (the intro roar counts too), for every player in the room. Built on installed packages where they fit:
- **aiKit** (Watchful Minds): the boss's decisions are an `aiKit.bt` behaviour tree (asleep, finished, dying, phase change by health fraction in aiKit's boss-preset shape, waking, busy, next attack). The 2D moves stay pixelBosses' own (see Notes for why aiKit's Brain does not drive them).
- **SecondWind**: hit points live in a `SecondWind.pool` health record on the boss's authority (its damage rules, death), mirrored into the synced `health` field.
- **juiceKit**: every sword hit bursts juiceKit sparks where the blade met the body on every player's screen; the killing blow adds a flash, a burst and juiceKit's critical hit stop (`pixelBosses.feel`).
| Thorn Knight | Hive Queen | Iron Warden |
|---|---|---|
|  |  |  |
## The bosses
Every attack is telegraphed: the boss flashes and winds up for about half a second, and thorns, missiles and lasers show a blinking marker where they will land before they do.
| Boss (`kind`) | Phase 1 | Phase 2 (at or below half health) |
|---|---|---|
| **Thorn Knight** `thornKnight` "Warden of the Moss" (24 hp) | Walks toward you; **charge** across the floor to the wall (low lunge: jump it); **leaping slam** onto where you stand that sends **shockwaves both ways** along the floor (jump them). | Faster and shorter rests; **thorn rain**: red markers blink on the ceiling, then thorns fall in two waves (the second wave strikes the gaps of the first); **triple dash** wall to wall to wall. |
| **Hive Queen** `hiveQueen` "Mother of the Swarm" (22 hp, flies) | Hovers above you; **swoop** in a dive through where you stand and up the other side (jump or dash over); **fan** of 5 slow orbs aimed at you. | Two fans of 7; **spiral**: flies to the middle and spins three arms of slow orbs for 2.6 s; **summons 2-3 stingers** that home weakly on their target and die in one hit. |
| **Iron Warden** `ironWarden` "Engine of the Sunken Vault" (26 hp) | Stands at one side of the arena and **hops** to the other (landing shakes the room); **fist slam**: yellow stripes mark the floor, then a piston fist shoots 9 tiles along it (jump it); **laser sweep** at foot height (**jump**) or head height (**stay on the ground**), shown by a blinking red line first. | **Missile barrage**: crosshairs mark columns on the floor, then missiles fall in two waves (the second strikes the gaps); **double laser**: one height, then the other. |
## Put a boss in your level
```lua
-- scenes/<yours>.scene/build.luau
local PP = require("twoDKit.api")
local ROOM = [[
########################
#......................#
#......................#
#......................#
#......................#
#......................#
#......................#
#......................#
#......................#
#......................#
#..P...................#
########################
]]
function content()
PP.level({ theme = "cave", text = ROOM })
PP.player({ character = "knight", lives = 5 })
-- a BossSpawn: in play one peer spawns the boss every player shares (its health, phase and moves replicate)
local spawner = entity.spawn("BossSpawn", { position = { 18, 1, 0 } }) -- the boss's feet on the floor
spawner.component.add("pixelBosses.BossSpawn", {
bossName = "Boss", -- every peer finds the boss by this name
kind = "thornKnight", -- or "hiveQueen", "ironWarden"
arenaMinX = 1, arenaMinY = 1, arenaMaxX = 23, arenaMaxY = 11, -- inside the walls; floor = arenaMinY
})
end
```
The boss waits, `dormant`, until something wakes it. From a trigger, a door or your arena kit, in play, on any peer:
```lua
local Bosses = require("pixelBosses.api")
local id = Bosses.byName("Boss") -- nil until the boss exists on this peer
local boss = Bosses.get(id) -- the Boss2D component
boss:activate() -- dormant -> intro roar -> fighting
boss:damage(1, playerBody.id, 1) -- 1 damage from a player, knocked right
boss:reset() -- full health, dormant, back at the start, shots cleared
print(boss.health, boss.maxHealth, boss.phase, boss.state, boss:isDefeated())
```
With **slash2D** installed, the boss is already a slash target on every peer: hit it with the sword and it takes damage. Any other attack system can test against `Bosses.hitbox(id)`.
## API
### `Boss2D` component (`pixelBosses.Boss2D`)
| Field | Kind | What |
|---|---|---|
| `kind` | enum, synced | `thornKnight`, `hiveQueen` or `ironWarden`. |
| `arenaMinX`, `arenaMinY`, `arenaMaxX`, `arenaMaxY` | numbers, synced | Arena bounds in world units. `arenaMinY` is the floor the boss and its shockwaves stand on, `arenaMaxY` the ceiling thorns and missiles fall from. All 0 = 12 units either side of the start and 12 up. Players inside it are the boss's targets. |
| `maxHealth` | number, synced | 0 = the kind's default (24 / 22 / 26 hits of 1 damage); the authority writes the resolved value in play, so reading it gives the real maximum. |
| `health` | number, synced, read-only | Hit points left. |
| `phase` | number, synced, read-only | 1, then 2 once health is at or below half. |
| `state` | string, synced, read-only | `dormant`, `intro`, `fighting` or `defeated`. |
| `move` | table, synced, read-only | The move it is running (`kind`, `t0`, `dur`, ...): what every peer simulates from. |
| `contactDamage` | bool | Touching the body hurts (default on). |
| `debugLabel` | bool | A small label above the boss with name, health, phase, state and move (this peer). |
| `sound` | bool | Boss sounds on this peer. |
Methods, callable on any peer (they travel to the authority): `activate()`, `reset()`, `damage(amount, attackerId?, dirX?) -> boolean` (false while it cannot be hurt: dormant or defeated; the intro roar can be hit), `isDefeated()`, `hitbox() -> { x, y, halfW, halfH }?`, `hazards()` (every live hurting box on this peer), `displayName()`, `maxHp()`.
### `pixelBosses.api`
```lua
local Bosses = require("pixelBosses.api")
Bosses.list() --> { "thornKnight", "hiveQueen", "ironWarden" }
Bosses.info("thornKnight") --> { id = "thornKnight", name = "Thorn Knight", title = "Warden of the Moss", maxHealth = 24, phases = 2 }
Bosses.all() --> every Boss2D entity id on this peer
Bosses.get(bossEntityId) --> its Boss2D component
Bosses.hitbox(bossEntityId) --> { x, y, halfW, halfH } (centre, world units) or nil while dormant / defeated
Bosses.on("phase", function(bossEntityId, phase) end)
Bosses.on("defeated", function(bossEntityId) end)
Bosses.on("hurt", function(bossEntityId, health, maxHealth) end)
Bosses.on("state", function(bossEntityId, state, previousState) end)
Bosses.on("*", function(eventName, ...) end)
```
The events fire **on every peer**, each from the synced fields it sees change (so `hurt` fires once per frame in which health dropped, however many hits landed in it). Each `on` returns a connection with `:Disconnect()`.
### How a boss hit costs a player: `Bosses.hurtPlayer`
Every peer tests **only its own player** (twoDKit's local player body) against the boss body, its projectiles, shockwaves, lasers, fists, missiles and stingers. A hit goes through one function you can replace:
```lua
Bosses.hurtPlayer = function(body, info)
-- info = { label = "Thorn Knight", damage = 1, fromX = <x of what hit>, boss = <boss entity id>, kind = <move kind> }
-- default: require("Trapline.api").hit(body, { label = info.label }) (costs a Trapline life)
end
Bosses.INVULNERABLE = 1.0 -- seconds after a boss hit before this player can take another
```
It runs only on the peer that owns `body`, at most once per `Bosses.INVULNERABLE` seconds, so one attack never hits every frame. A metroidvania replaces it with a mask loss plus knockback away from `info.fromX` instead of Trapline's respawn at the checkpoint.
## Multiplayer
- One peer runs the boss: the owner of its entity. It picks targets among the players inside the arena and writes each move once into the synced `move` field.
- Every peer computes the same pose, projectiles, telegraphs, sounds and shakes from that move on Trapline's shared clock (`Bosses.now()`), so nothing per projectile crosses the network. Stingers are steered on each peer toward their target and their deaths are broadcast.
- `damage`, `activate` and `reset` called on another peer are sent to the authority, which applies them; `health`, `phase` and `state` replicate back and the events fire everywhere. So two players with their own swords both hurt the same boss: the attacker's peer tests its swing against the boss where that peer draws it, flashes the boss at once and sends the damage on the `pixelBosses.damage` channel; the authority applies it once (a repeated request is ignored).
- Every peer sees every hit: slash2D syncs each counted hit, and each peer flashes the boss and plays the juiceKit sparks from it; the health drop arrives through the synced `health`.
- Put the boss in a scene with a `BossSpawn` (as above), not with `entity.spawnSynced` inside the scene build: a build-spawned synced boss reached a peer that entered play after the first with no replication record (its state, health and moves never arrived there; engine report filed). The BossSpawn waits until the room has answered this peer's join, finds the boss by name, and when the room has none the lowest peer id spawns it at runtime with `entity.spawnSynced` (a peer further down waits longer, in case the lowest never does); a duplicate from a race is despawned by its owner. A late joiner gets the room's boss, the owner leaving hands it to a peer that stays, and re-entering play never makes a second one. In edit mode it shows nothing.
- A boss you spawn yourself at runtime with `entity.spawnSynced` plus a Boss2D works the same way; a plain `entity.spawn` boss still works for one player, but the other players would each fight their own.
## What is inside
| Asset | What |
|---|---|
| `BossSpawn` (component) | Puts one networked boss in play on whichever peer should spawn it; `bossId()`, `boss()`. |
| `Boss2D` (component) | The boss: AI on the authority, drawing, hazards, hits on this peer's player, events, slash2D registration. |
| `api` (module) | `list`, `info`, `on`, `all`, `get`, `byName`, `hitbox`, `hurtPlayer`, `now`, and the network routing. |
| `moves` (module) | Every attack as a pure function of time: `pose`, `hazards`, `cues`, and the AI `plan`. Tune the timings in `Moves.KNIGHT`, `Moves.QUEEN`, `Moves.WARDEN`. |
| `defs` (module) | Names, titles, health, sheet layout, body boxes, sound names, and `PHASES` (the health fractions each phase starts below). |
| `feel` (module) | The juiceKit presets `pixelBosses.hit` (sparks) and `pixelBosses.finish` (killing blow); `Feel.enabled`. |
| `art` (module) | Paints the four sheets in code with pixelPaint: `require("pixelBosses.art").generate()` repaints them. |
| `sfx` (module) | The 15 boss sounds (chipSfx voices) and `bake()` to re-bake them; `BSfx.volume`, `BSfx.muted`. |
| `art/` | `thornKnight` (64 x 64 frames), `hiveQueen` (80 x 64), `ironWarden` (64 x 80) and `fx` (16 x 16) sheets with their materials. |
| `sounds/` | The baked sound clips. |
| guide | `how-to-add-a-boss-fight-to-a-2d-platformer`. |
## Notes and limits
- Bosses use twoDKit's camera shake and pixel effects, and their own hit-stop (released every frame it is due, so it can never stick).
- The sprites face right and are drawn with pixelSprites' `sprite` shader: crisp at twoDKit's pixel-perfect camera.
- The Iron Warden stands 2.2 units in from each wall; make the arena at least 16 units wide so its lasers and fist leave room.
- A stinger chases the player the boss targeted; on other peers it may sit a little differently, since each peer steers its own copy.
- Why aiKit's Brain component does not move the bosses: `Brain` adds a navKit `NavAgent` and moves with `actions.moveTo` on a 3D navmesh, turns by yaw, senses through 3D sight cones (`senses`) and reads health from SecondWind `Vitals` (`registry.healthFraction`). A side-view boss moves in arcs, charges and swoops on a 2D plane computed from one synced move on a shared clock, and its entity never moves (its sprite does), so Vitals' effects and aiKit's movement would both sit at the spawn spot. aiKit's behaviour tree (`aiKit.bt`, pure, no navKit) and its boss rule (phases by health fraction, a roar on each new phase) fit, and are what Boss2D uses.
## Changelog
- **1.2.3**: the description and README give the one-line install with this package's id. No code change.
- **1.2.2**: a boss stays a sword target after slash2D reloads during play: once a second each boss checks that slash2D still lists it and registers again (with its hit flash and sparks) when it does not. Before, a reload of slash2D mid-session left every boss unhittable until the scene restarted.
- **1.2.1**: the bosses' sprite sheets ship as textures only; pixelSprites 1.1.0 builds their materials at runtime (`Sprites.sheetMaterial`), so the package carries no material assets and no generated preview pictures. Nothing changes in a fight.
- **1.2.0**: `BossSpawn` component: a boss placed in a scene now reaches every player. Bosses built with `entity.spawnSynced` inside a scene build never synced to a peer that entered play second (it read dormant at full health while the first player fought it down). The spawner puts the boss in at runtime from exactly one peer, late joiners get it, a leaving owner hands it on, re-entering play makes no duplicate. `Bosses.byName(name)`; the spawn-once decision is `Bosses._spawnPlan`, covered by tests.
- **1.1.0**: every sword hit lands and counts: hits during the intro roar now count (they used to be refused, which looked like a miss), checked on all three bosses in both phases at every moment of every move from the left, the right and above (a regression test). The authority decides with an aiKit behaviour tree; health lives in a SecondWind pool; sword hits play juiceKit sparks on every peer and the killing blow a flash and a critical hit stop. Second-player damage path tested (`Bosses._receiveDamage`). `Bosses.get` always returns the entity's live Boss2D (a proxy kept from before a reload or a re-add took no writes, so every hit and command sent to it was lost), and the network handlers of an earlier copy of the api go quiet after a reload instead of applying a hit twice. New dependencies: aiKit, SecondWind, juiceKit.
- **1.0.4**: fixed the boss being unhittable where you see it: its sword hit box stayed at the spot where it first appeared instead of following it as it walks, charges and leaps. It now follows the boss on every player's screen, and a swing at the empty spawn spot no longer hurts it. Needs slash2D 1.0.3.
- **1.0.3**: dependencies pinned by guid; a test suite (`zero tests run pixelBossesTests`).
- **1.0.2**: preview images; runs on twoDKit 1.3.0.
- **1.0.1**: the boss entity is spawned synced by sideScrollerKit; preview images.
- **1.0.0**: first release: Thorn Knight, Hive Queen and Iron Warden, two phases each, Boss2D, the api, painted sheets, 8-bit sounds, slash2D hook-up and the guide.
# slash2D: a Hollow Knight style sword slash for 2D platformers
Give a **twoDKit** platformer player a nail slash in one line. Press attack and a crisp, four-frame pixel slash arcs out where you face; hold **up** to slash upward, hold **down in the air** to slash downward. A hit freezes the game for a beat (hit-stop), shakes the camera, bursts a pixel spark and plays an 8-bit clank; a side hit pushes you back a little, and a **down-slash hit pogos you** upward and refills your dash, so you can bounce across spikes and enemies. Every player sees every other player's swings and sparks.
Anything can be hit: register an entity with `Slash.addTarget` and you get an `onHit` call with the damage and direction. Entities with **SecondWind** `Vitals` (health) are hit automatically through SecondWind's own multiplayer-safe damage, so existing enemies and training dummies work with no code.

## Install
In the engine shell: `zero zeromind installAsset 37cb0d20-956d-46d3-b41f-697f4ba888b7` (or search ZeroMind for "slash2D" or "2D sword slash"). It needs twoDKit (which brings controlsKit, pixelSprites, pixelPaint, chipSfx, Trapline and SecondWind).
## Use it (works as written)
In a scene's `build.luau`:
```lua
local PP = require("twoDKit.api")
function content()
PP.level({ theme = "cave" })
local players = PP.player({ character = "knight" })
players.body.component.add("Slash2D", {})
PP.hud()
end
```
Press Play and attack with **X**, **H** or the **left mouse button**, the pad's **right trigger** (or left shoulder), or the **ATTACK** touch button beside jump.
Make something hittable (in a component, or a scene's `entrypoint.luau` `onLoad`, on every peer):
```lua
local Slash = require("slash2D.api")
local dummy = entity.find("Dummy")
local handle = Slash.addTarget(dummy.id, {
halfW = 0.4, halfH = 0.6, offsetY = 0.6, -- a box around its feet position, in tiles
onHit = function(hit)
print("hit for", hit.damage, "from", hit.attacker, "dir", hit.dirX, hit.dirY)
return true -- false refuses the hit (no spark, no pogo)
end,
})
-- later: Slash.removeTarget(handle)
```
## Controls
Slash2D switches its body's `Player2D.scheme` from `platformer` to **`platformerSlash`** when play starts (set `useScheme = false` to leave it). `platformerSlash` is controlsKit's `platformer` plus `attack`:
| Device | Attack |
|---|---|
| Keyboard | `X`, `H` (J stays dash, K jump) |
| Mouse | left button |
| Gamepad | right trigger, or left shoulder |
| Touch | ATTACK, in the right-hand diamond beside jump (crouch moves to a small button above it) |
Directions come from `move`: up held = up slash; down held while airborne = down slash; otherwise the way you face.
Another kit can extend the scheme:
```lua
local Slash = require("slash2D.api")
local CKSchemes = require("controlsKit.schemes")
local s = Slash.schemeWithAttack("platformer")
s.actions.map = { kind = "button", label = "Map", keys = { "KeyM", "Tab" }, pad = { "back" } }
CKSchemes.register("metroidvania", s)
-- then set Player2D.scheme = "metroidvania" and Slash2D.useScheme = false
```
## API (`local Slash = require("slash2D.api")`)
| Call | What |
|---|---|
| `Slash.addTarget(entityId, opts) -> handle` | Make an entity hittable on this peer. `opts`: `halfW`, `halfH` (half extents, tiles), `offsetX?`, `offsetY?` (box centre from the entity's position), `box?() -> { x, y, halfW, halfH }?` (a live box that replaces the entity-based one, for a target drawn away from its entity; nil = not hittable now), `onHit(hit) -> boolean?`. `hit = { damage, dirX, dirY, attacker, x, y }` (attacker = the body's entity id, x/y = where the boxes overlap). Return `false` to refuse; `true` or `nil` counts the hit. |
| `Slash.removeTarget(handle)` | Stop it being hittable. |
| `Slash.on("swing" \| "hit" \| "*", fn) -> conn` | Events on every peer. `swing`: `{ player, dir, dirX, dirY, x, y, isLocal }`. `hit`: `{ player, target, damage, dir, dirX, dirY, x, y, isLocal, pogo }`. `conn:Disconnect()`. |
| `Slash.schemeWithAttack(baseName) -> scheme` | A fresh copy of a controlsKit scheme with `attack` added (keys, pad, touch), for you to extend and register. |
| `Slash.SCHEME` | `"platformerSlash"`. |
| `Slash.targets()`, `Slash.isTarget(id)`, `Slash.overlaps(...)`, `Slash.VERSION` | Helpers. |
**How hits travel.** Targets are registered on every peer. The attacking player's own peer tests the swing against each target's box at the entity's *current* position and calls `onHit` **on that peer**, so the target's code routes damage to whoever owns the target (a synced field, a message, or `SecondWind.api`'s `damage`, which does that for you). The swing and the spark reach every peer through two synced fields on Slash2D.
## Slash2D fields
| Field | Default | What |
|---|---|---|
| `action` | `attack` | controlsKit action that swings. |
| `damage` | `1` | Damage passed to `onHit`. |
| `cooldown` | `0.33` | Seconds between swings. |
| `reach`, `width` | `1.8`, `1.3` | Hitbox in tiles: side = reach wide x width tall; up/down = width wide x reach tall. |
| `active` | `0.12` | Seconds a swing can land hits (each target once per swing). |
| `pogoSpeed` | `15` | Bounce speed (tiles/s) on a down-slash hit; 0 = off. Refills the dash. |
| `recoil` | `0.4` | Tiles you are pushed back on a side hit (stops at walls). |
| `hitStop`, `shake` | `0.055`, `0.12` | Hit-stop seconds (juiceKit hitstop, real time, cannot stick) and camera shake (twoDKit Camera2D) on your own hits. |
| `useScheme` | `true` | Switch Player2D's `platformer` scheme to `platformerSlash`. |
| `hitVitals`, `vitalsDamage` | `true`, `20` | Hit SecondWind Vitals and how much. |
| `vitalsHalfW`, `vitalsHalfH` | `0.5`, `0.6` | Box used for a Vitals entity (centred `vitalsHalfH` above its position). |
| `hitPlayers` | `false` | Also hit other players' Vitals (PvP). |
| `effects` | `true` | Draw and play sounds on this peer. |
| `swing`, `hitFx` | | Synced, read-only: the last swing and hit. |
Methods: `swingNow(dir?)` (owner; swing now), `hitbox()`, `counts()`.
## What is inside
- `Slash2D.component`: the attack. `api.module`: targets, events, schemes. `schemes.module`: `platformerSlash` and `withAttack`.
- `art/slash.texture` + `slash.material`: the 4 x 4 sheet (side, up, down slash, hit spark), painted by `painter.module` with pixelPaint; drawn with pixelSprites.
- `sounds/`: `swing`, `hit`, `pogo`, synthesised with chipSfx by `sfx.module` (they follow chipSfx's volume and mute).
- Guide: **How to add a sword slash attack to a 2D platformer** (`slash2D.package/how-to-add-a-sword-slash-attack-to-a-2d-platformer`).
## Changelog
- **1.0.10**: the description and README give the one-line install with this package's id. No code change.
- **1.0.9**: `Slash.VERSION` names the release again (1.0.8 still read 1.0.7).
- **1.0.8**: states controlsKit 1.2.8, the release every part of sideScrollerKit now shares (no code change).
- **1.0.7**: the sword always swings. When the live controlsKit scheme in the build Slash2D reads has no `attack` action (a world can hold several controlsKit builds, and a game's own scheme can land in another one), Slash2D reads the attack's default buttons straight from the engine's input: X, H, left mouse, the pad's right trigger or left shoulder. New `Slash.attackDown()`.
- **1.0.6**: `Slash.useScheme(name, scheme)`: a game that gives the player its own scheme (with an `attack` action) registers it in the controlsKit build slash2D reads and switches that build to it, so the attack button reads even when the world holds several controlsKit builds.
- **1.0.5**: the slash sheet ships as a texture only; pixelSprites 1.1.0 builds its material at runtime, so the package carries no material asset and no generated preview picture. The sword plays exactly as before.
- **1.0.4**: the hit stop on your own hits is juiceKit's (`juiceKit.hitstop`: one keyed time-scale hold with a real-time watchdog, so it can never stay stuck after a scene swap, which twoDKit's freeze could). Regression test for live target boxes. New dependency: juiceKit.
- **1.0.3**: a target can give a live hit box (`box` in `Slash.addTarget`, read with `Slash.targetBox`), so something drawn away from its entity, like a moving boss, is hit where it is seen.
- **1.0.2**: dependencies pinned by guid; a test suite (`zero tests run slash2DTests`).
- **1.0.1**: preview images; runs on twoDKit 1.3.0.
- **1.0.0**: first release.