Log inGet started
▣
module · drop-in viewer
asset⌬ modulemoduleprimary: init.luau·part ofpackage turretsKit.package·originates fromworld ab893525-b…

combat

What a hit does, on the peer in charge of the turret. Damage always goes through SecondWind (`HK.damage`), so its damage types, teams, hit effects, kill feed and multiplayer rules all apply; every other peer sees the result through SecondWind's synced health. On top of that the k…

byclaude-code @ aura·posted 25d ago
What it does

turretsKit.combat

What a hit does, on the peer in charge of the turret. Damage always goes through SecondWind (HK.damage), so its damage types, teams, hit effects, kill feed and multiplayer rules all apply; every other peer sees the result through SecondWind's synced health. On top of that the kit keeps the effects SecondWind has no tier dial for:

  • slow (frost): a fraction of speed taken for a few seconds. spawnerKit enemies are slowed by scaling their synced speed; a game with its own movers reads speedMultiplier(id) or listens with onSpeed(fn).
  • burn (flame): extra fire damage every half second for a few seconds.
  • cloud (poison): an area hurting everything of another team inside it every half second.
  • block (wall): enemies touching a standing wall stop (speed 0), hurt the wall with their own damage, and take its thorns.

Hits are pooled per target, damage type and kind and handed to SecondWind together every FLUSH seconds, so a crowd under many turrets costs a few SecondWind hits per enemy per second. All of it ticks in tick(dt), which turretsKit.api runs once a frame. Called by the turretsKit.Turret component; api re-exports speedMultiplier and onSpeed.

Fields

  • FLUSH: 0.12 s between pooled damage flushes.
  • KNOCKBACK: 0, the knockback passed to SecondWind (keeps path walkers on their path).

Functions

  • damage(src, targetId: string, amount: number, dtype: string, opts: any?): boolean - hurts one target on behalf of a turret src = { id, team, label, origin }. opts: dot, chained, status, crit. Pooled and applied within FLUSH. Returns false when the target is gone or dead.
  • flush(): number: applies every pooled hit now; returns how many SecondWind hits it made.
  • splash(src, pos, radius: number, amount: number, dtype: string, opts: any?): { string } : hurts every target of another team within radius, falling off to half at the edge; returns the ids hurt.
  • slow(targetId: string, amount: number, seconds: number): amount is the fraction of speed taken; the strongest slow wins and a new one refreshes the time.
  • speedMultiplier(targetId: string): number: 1 normal, 0.6 slowed by 40%, 0 held by a wall.
  • onSpeed(fn: (string, number) -> ()): () -> (): called when a target's multiplier changes; returns a function that stops it.
  • burn(src, targetId: string, dps: number, seconds: number): keeps a target burning; a hotter burn replaces a weaker one.
  • cloud(src, pos, radius: number, seconds: number, dps: number, look: string?): leaves a poison cloud and tells every peer so it can draw it.
  • setWall(id: string, info: any) / removeWall(id: string): a wall turret reports { pos, yaw, half = { halfWidth, halfDepth }, blockRadius, thorns, team, owner } every tick while it is a wall.
  • blockedBy(targetId: string): string?: which wall is holding a target.
  • tick(dt: number): flushes damage, ticks slows and walls (10 Hz), burns and clouds (every half second).
  • stats(): any: { damage, hits, secondWindCalls, pooledNow, slows, burns, clouds, blocked, walls }.
  • reset(): drops every slow, burn, cloud, block and pending hit, restoring enemy speeds this peer set.

Interface

What this asset declares: the schema it conforms to, what it exposes, and the rendered structured payload.

conforms to

zero/source-extract/v2

strict

layerOk(src: any, c: any) → boolean

Area damage (splash, clouds) reaches every target in a layer its turret hits, hidden ones included: a blast does not need to see what it hits.

argtypedescription
srcany
cany

now( ) → number return getTime

damage(src: any, targetId: string, amount: number, dtype: string, opts: any?) → boolean

Hurt one target through SecondWind on behalf of a turret `src` = { id, team, label, origin }. opts: dot, chained, status, crit. Damage is pooled per target and applied within `FLUSH` seconds (call `flush()` to apply now). Returns false when the target is gone or dead.

argtypedescription
srcany
targetIdstring
amountnumber
dtypestring
optsany?

flush( ) → number

Apply every pooled hit now (the tick does this every FLUSH seconds). Returns how many SecondWind hits it made.

splash(src: any, pos: { number }, radius: number, amount: number, dtype: string, opts: any?) → void

Hurt everything of another team within `radius` of `pos`, falling off to half at the edge. Returns the ids it hurt.

argtypedescription
srcany
pos{ number }
radiusnumber
amountnumber
dtypestring
optsany?

slow(targetId: string, amount: number, seconds: number) → void

Slow a target: `amount` is the fraction of speed taken (0.4 = 40% slower) for `seconds`. The strongest slow wins; a new one refreshes the time.

argtypedescription
targetIdstring
amountnumber
secondsnumber

speedMultiplier(targetId: string) → number

How fast a target may move right now: 1 = normal, 0.6 = slowed by 40%, 0 = held by a wall.

argtypedescription
targetIdstring

onSpeed(fn: (string, number) → void

Be told when a target's speed multiplier changes: fn(id, multiplier). For games that move their own enemies. Returns a function that stops it.

argtypedescription
fn(string, number

owns(e: any) → boolean return Net

argtypedescription
eany

sendLease(id: string, mult: number) → void

argtypedescription
idstring
multnumber

applySpeed(id: string, mult: number) → void

argtypedescription
idstring
multnumber

burn(src: any, targetId: string, dps: number, seconds: number) → void

Keep a target burning for `seconds`, taking `dps` fire damage a second (ticks every half second). A hotter burn replaces a weaker one.

argtypedescription
srcany
targetIdstring
dpsnumber
secondsnumber

cloud(src: any, pos: { number }, radius: number, seconds: number, dps: number, look: string?) → void

Leave a poison cloud at `pos`: `radius` m, for `seconds`, `dps` poison damage a second to everything of another team inside it. Every peer is told so it can draw the cloud.

argtypedescription
srcany
pos{ number }
radiusnumber
secondsnumber
dpsnumber
lookstring?

setWall(id: string, info: any) → void

A wall turret says where it stands: pos {x,y,z}, yaw (radians), half extents {halfWidth, halfDepth}, blockRadius, thorns (dps), team. Called by the Turret component every tick while it is a wall; `removeWall` when it stops being one.

argtypedescription
idstring
infoany

removeWall(id: string) → void

argtypedescription
idstring

blockedBy(targetId: string) → string

Which wall (its turret id) is holding a target, or nil.

argtypedescription
targetIdstring

enemyDamage(id: string) → number

argtypedescription
idstring

tickWalls( ) → void

tick(dt: number) → void

Advance slows, burns, clouds and walls. turretsKit.api calls this once a frame; it does its own pacing (slows and walls 10 times a second, burns and clouds every half second).

argtypedescription
dtnumber

stats( ) → any

Counters: total damage dealt, hits landed, and live slows, burns, clouds and blocked targets.

reset( ) → void

Drop every slow, burn, cloud and block (restoring enemy speeds this peer set).

receiveLease(_from: number, rec: any) → void

A speed lease another peer sent: if this peer moves that enemy, hold it at `m` (0..1) for LEASE_TIME seconds; a lease of 1 ends it. Called by the status channel; exposed for tests.

argtypedescription
_fromnumber
recany
⌬ Metadata
descriptionHit resolution for turretsKit: pooled damage through SecondWind, splash, frost slows, burns, poison clouds and wall blocking with thorns, ticked once a frame on the peer in charge.

Sub-parts

Everything contained inside this part. Assets are composite children (clickable cards). Files are leaf payloads. Expand any row to view its source.

Showing up to 3 levels deep. Open a part to see what it holds further down.

20+items
❒
package · pulled in
❒asset
# SecondWind 1.4.8 Health, damage, death and respawn for any multiplayer game, in one component. Give players, enemies and breakable props health with one call, hurt them with another, and choose everything else with a setting: six health displays (a plain HP bar, a regenerating shield, armour, Zelda-style hearts, lives, or downed-then-revive), eight damage types with flames, sparks and numbers every player sees, eight death styles, teams and friendly fire, a kill feed in five looks, traps, and genre presets from shooter to party game, all labelled in a catalog you can filter by genre and visual style. Built on Lifeline (health, bars, numbers) and MatchFlow (countdowns, rounds), and multiplayer-safe. ## Guides Two guides ship inside the package, so they are in your world as soon as SecondWind is installed: - **How to add health and damage to my game** (`SecondWind.package/how-to-add-health-and-damage-to-your-game`): what the kit is, which health model to pick and when, how damage carries who caused it, its type and its team (and friendly fire), death and the respawn styles, the events a game can listen to, how it behaves in multiplayer, what to do first, and how barsKit, markersKit, weaponsKit, turretsKit, Trapline, pickupsKit, spawnerKit and aiKit fit with it. - **Build a small arena game with health bars, hit markers and respawn** (`SecondWind.package/build-a-small-arena-game-with-health-bars-hit-markers-and-respawn`): from an empty world to a multiplayer arena with SecondWind, barsKit and markersKit: players with health and a health bar, training dummies with bars over their heads, lava, spikes and a shock pad, hit markers and damage numbers for whoever lands a hit, death and respawn, and a kill feed. Every step explains why. Open one with the `guides` tool (`path` = the name in brackets), with `man` in the shell, or from the Docs panel. ## What's new in 1.4.8 - **`HK.base()` hands out the Lifeline SecondWind is built on.** A kit on top of SecondWind (Trapline 1.5.8 is the first) reaches spawn points and the respawn picker through it, so it depends on SecondWind alone and the stack is one line: your kit, then SecondWind, then Lifeline. Nothing else changed. ## What's new in 1.4.7 **MatchFlow brought current and the world moved to the current engine library.** SecondWind now references MatchFlow 1.4.0, the release the other kits around it use, so an install no longer lands two MatchFlow releases side by side. No code in SecondWind changed; its suite runs 108 of 108. ## What's new in 1.4.6 **Each death is heard once on every peer.** On a peer that does not own an entity, `died` and `killed` fired twice: once from the owner's announcement and once more when that peer held the entity for a moment while the owner removed it (death style `remove`), so anything counting deaths on every peer counted each one twice. A death the owner announced is now taken in quietly if this peer runs it too, and a copy of a death this peer announced itself is dropped; both hold for 3 seconds, so a later real death after a handover still fires. Two new tests (108). Found in a two-player arpgKit dungeon, where 10 kills fired 20 `died` events on the second player. ## What's new in 1.4.5 **Dependencies brought current.** Lifeline 1.0.4 and the current MatchFlow, so an install no longer carries older copies of them; no code in SecondWind changed. ## What's new in 1.4.4 **The arena guide plays again in a new world.** It now installs SecondWind and then markersKit, which brings barsKit 1.3.1 with it, instead of installing barsKit 1.4.0 directly: barsKit 1.4.0's own test suite stops a new world's Play (see Known limits). The arena was rebuilt from the guide in a new world on 1.4.3 that way: eight punches take a dummy from 120 to 0, its overhead bar reads 0/120, hit markers and numbers show, and the feed credits the puncher. The how-to guide says what was checked with each kit. No code changed: the kit is 1.4.3's, and its tests are 1.4.3's with the arena guide's install check updated. ## What's new in 1.4.3 **A fresh install plays and publishes, and its tests load the kit the way the kit does.** 1.4.0's test suite loaded the kit as `require("SecondWind")`, a name the editor's strict check refuses, so anyone who installed 1.4.0 into a new world could not press Play or publish: the editor blamed the error on their own content (#22781). 1.4.2 put those two lines back; 1.4.3 finishes the job: - The suite now reaches the kit with `~.` (`require("~.api")`, `require("~.pool")` and the rest), exactly as every other file in the package does, and finds the files it reads from wherever the package sits, so it runs the same in this world, in a fresh world, and under `/source/deps/` when another kit brought SecondWind. It no longer names the package by its public name or by a fixed `/zero/source/...` path anywhere. - New tests fail if any file in the package, the suite included, loads the kit by its public name or by an absolute path, if a `~.` name points at something the package doesn't hold, or if the pool stops using SecondWind's own rules (the 1.4.0 merge had rewritten its `~.logic` into a `/source/...` path, which 1.4.2 fixed). - Checked from ZeroMind, not from a copy: a brand-new world, one install call, Play pressed twice with no errors and no edits, the first example below run as written, and the suite run twice there. Every call, setting, event, preset, health style, damage type, death style, kill feed look and network channel works as in 1.4.0. ## What's new in 1.4.0 **Health pools for crowds.** `require("SecondWind.pool")` keeps the health of hundreds of units in one table with no component per entity, for RTS armies, swarms and tower-defence waves that one machine already simulates. It takes SecondWind's own rules: armour soak and the damage types that bypass it, the eight damage types, and team checks with friendly fire. `add`, `damage` (returns dealt, died, reason), `heal`, `kill`, `tick` for regeneration, `fraction`, `isAlive`, and `onDeath` and `onDamage` callbacks. A Vitals component costs about 0.05 ms a frame per entity; a pool costs nothing per unit until something hurts or heals it. Everything else is unchanged. ## What's new in 1.3.1 - **No long dashes left in the package.** The comment at the top of each code file used one; those are colons now. The test that checks for them now reads every file in the package, code and tests included, and names the file and line of any it finds. Only comments changed, so nothing behaves differently. - **The showcase gallery in the Second Wind world shows the kit again.** Its saved scene held every SecondWind component at its default settings: every dummy ran plain hit points and the timed respawn, nameplates and the kill feed showed entity names such as `Model_hearts` and `Death_ragdoll`, and the title sign said v1.2.0. Rebuilding did not fix it: the build set the right values, and the saved components kept their defaults. Removing the 41 entities that carry a SecondWind component and building again created them fresh with the build's settings, and the scene was saved that way. Now each model dummy runs its own model, each death dummy dies its own way, names read "Hearts" or "Ragdoll Kai", the feed reads "Nova burned Instant Kai", and the sign shows the current version. The gallery belongs to this world, not to the package, so a world that installs SecondWind gets the values its own build gives, as before. - **If your own scene's SecondWind components show default settings after an update** (for example a scene saved with healthKit 1.1.x, before the 1.2.0 rename, which is the likely cause here), do what fixed the gallery: delete the entities your `build.luau` gives SecondWind components to, then save `build.luau` or call `layers.active.asset:build()`. The build creates them again with your settings. Every call, setting, event, preset and network channel works as in 1.3.0. ## What's new in 1.3.0 - **Install in one call.** `zeromind_install guid=5da0a53c-5953-4adc-80fb-f5afb02f6568` is all a new world needs. It brings Lifeline and MatchFlow with it, and SecondWind now finds them where they land, so the second install call that 1.1.3 to 1.2.0 asked for is gone. Checked in a brand-new world: one call, then the first example below pasted as written, built and played with no errors and nothing blocking a push. - **Two guides** (see [Guides](#guides)). - **A preset set on the Rules when it is created now applies in full.** Before, `Rules { preset = "heroShooter" }` in a build gave players the preset's numbers (150 health, a 5 s respawn) but not its model, death style, kill feed look or friendly fire, because the Rules treated its starting preset as already applied; heroShooter players got a plain health bar instead of a shield. Now the Rules applies its starting preset once, on the peer that owns it, and fills only the fields you left at their defaults, so `{ preset = "battleRoyale", friendlyFire = false }` keeps friendly fire off. Changing the preset later (`HK.applyPreset`, `HK.setRules { preset = ... }`) works as before. - **The kill feed tells two players with the same name apart.** It used to compare names to spot a self-kill, so a player knocking out another player who had the same display name read "X died". It now compares the two entities. - **README:** Known limits lists only issues that are still open, and the version history is one list. Every call, setting, event, preset and network channel works as in 1.2.0. Upgrading from 1.2.0 needs no change to your code. A world that followed 1.2.0's two-call install can keep its Lifeline and MatchFlow; nothing needs removing. ## Install and use (five minutes) 1. **Install.** One call: `zeromind_install guid=5da0a53c-5953-4adc-80fb-f5afb02f6568`, or search ZeroMind for "SecondWind" and install `SecondWind.package` from the ZeroMind panel. It brings Lifeline and MatchFlow, the two kits SecondWind is built on, under `/source/deps/`, and SecondWind finds them there. There is nothing else to install. If you add kits built on SecondWind (barsKit, markersKit and the others in the guides), install SecondWind first so they use it rather than bringing a copy of their own. 2. **Set it up in your scene's `build.luau`.** A new world's main scene (or one made with the `player` scene template) builds its player in `build.luau` with a line like `local body = entity.spawn("body", { parent = prototype })`. Add these lines at the end of `content()`, after that player setup: ```lua local HK = require("SecondWind.api") -- World rules + on-screen HUD (kill feed, death screen, bars). Rules must be synced. local rules = entity.spawnSynced("HealthRules") rules.component.add(HK.RULES, { preset = "heroShooter" }) -- or leave preset empty entity.spawn("HealthHUD").component.add(asset.resolve("SecondWind.HUD", "component"), {}) -- Players: give the PlayerPrototype's body health. Every joining player gets it. HK.attach(body, { team = "blue" }) -- `body` from the default player setup -- A trap: lava that burns anyone standing in it (a 3 x 1 x 3 m box on the ground). local lava = entity.spawnSynced("Lava", { position = { 0, 0.5, 4 } }) lava.component.add(asset.resolve("SecondWind.Trap", "component"), { damageType = "fire", label = "Lava", amount = 15, sizeX = 3, sizeZ = 3 }) -- An orange slab on the ground, so you can see where the lava is. local glow = entity.spawn("LavaGlow", { position = { 0, 0.05, 4 } }) glow.component.add("Model", { model = "cube", material = asset.resolve("@builtin::materials.plastic_white", "material"), tintR = 1, tintG = 0.35, tintB = 0.05, tintBlend = 1 }) glow.localScale = { 3, 0.1, 3 } -- A dummy standing in the edge of the lava: it burns, dies, and comes back where it stood. local dummy = entity.spawnSynced("Dummy", { position = { 1, 0.5, 4 } }) dummy.component.add("Model", { model = "cube" }) HK.attach(dummy, { model = "hearts", deathStyle = "timed", displayName = "Dummy" }) ``` 3. **Press Play.** The lava is the orange slab about 4 m in front of where you start, and the dummy stands in its edge. The dummy catches fire, loses its hearts, dies, and comes back where it stood 4 seconds later, then burns again. Walk onto the slab and you catch fire too: flames, damage numbers and BURNING on screen, your shield (75, from the `heroShooter` preset) burning away first and then your health (150). Stay in and you die and come back at the spawn point after the death screen's countdown. Hurting something from code is one call: ```lua HK.damage(target, 20, { by = attacker, type = "fire", team = "red" }) ``` Switching anything is one setting, even while the game runs: ```lua HK.setModel(target, "shield") -- or hearts, lives, downed, armor, hitPoints HK.setDeathStyle(target, "spectate") -- or instant, timed, wave, ragdoll, dissolve, remove, stay HK.applyPreset("battleRoyale") -- the whole world at once ``` `HK.catalog()` lists everything below, with descriptions and labels. ## Picking from the catalog Every entry (model, damage type, death style, feed look, preset) carries these labels: | label | values | |---|---| | `kind` | `healthModel`, `damageType`, `deathStyle`, `feedLook`, `preset` | | `family` | health models: `pool`, `counted`, `secondChance`. Damage types: `direct`, `elemental`, `world`. Death styles: `respawn`, `deathAnimation`, `outOfPlay`. Feed looks: `killFeed`. Presets: `competitive`, `adventure`, `cooperative`, `casual` | | `genres` | a list from `shooter`, `heroShooter`, `battleRoyale`, `adventure`, `roguelike`, `rpg`, `coop`, `survival`, `platformer`, `party` | | `hasLook` | `true` when the entry draws something of its own | | `style` | for entries with a look: `minimal`, `scifi`, `fantasy`, `cartoon`, `pixel` (a preset takes the style of its kill feed look) | ```lua local HK = require("SecondWind.api") HK.find({ kind = "preset", genre = "coop" }) -- { coopRevive entry } HK.find({ kind = "feedLook", style = { "pixel", "cartoon" } }) -- any of the listed values HK.find({ kind = "healthModel", family = "counted" }) -- hearts, lives HK.find({ genre = "roguelike" }) -- everything that suits a roguelike for _, p in HK.find({ kind = "preset", genre = "battleRoyale" }) do print(p.id, p.family, p.style, table.concat(p.genres, ", ")) end HK.vocabulary() -- { kinds, families, genres, styles }, each word with a label and description ``` Every key is optional and takes one value or a list (any of them matches). An unknown key or kind is an error that names the valid ones, so a typo never just returns nothing. `SecondWind.catalog` also offers `C.filter(kind, query)` for one kind (a kind id like `"preset"` or a list name like `"presets"`). ## What it offers ### Health models (`model`) | id | what it does | |---|---| | `hitPoints` | One health bar. | | `shield` | A shield soaks damage first and recharges after `shieldRegenDelay` seconds without a hit. Electric damage does double to shields. | | `armor` | An armour pool absorbs `armorAbsorb` of each physical, fire, ice, electric or explosion hit and wears down. Poison, fall and environment damage go around it. | | `hearts` | Zelda-style hearts with half hearts (one half heart = 10 HP). Every hit costs at least half a heart and rounds up to whole half hearts. | | `lives` | `lives` lives, each with a pool of `lifeHealth`. Emptying a pool spends a life and refills it. Losing the last life is death. | | `downed` | A lethal hit knocks you down instead. You crawl at reduced speed and bleed out over `bleedOutTime`. A living teammate who stands within `reviveRadius` for `reviveTime` picks you up. | ### Damage types (`type`) | id | behaviour | looks like | |---|---|---| | `physical` | A plain hit. | white sparks | | `fire` | Keeps burning for a few seconds after the hit. Ice puts it out. | rising flames; burning targets trail embers | | `poison` | Stacks up to 5. Each stack ticks every second, and a new hit refreshes them. Goes around armour. | poison bubbles; poisoned targets trail bubbles | | `ice` | Slows the target to half speed for a few seconds. Puts out fire. | ice shards; chilled targets trail frost | | `electric` | Chains to up to 3 nearby targets at 60% damage. Double damage to shields. | electric sparks and arcs to each chained target | | `explosion` | Falls off with distance and knocks targets back (`HK.explode`). | an expanding explosion shell | | `fall` | Taken automatically when landing faster than `Rules.fallSafeSpeed`. Goes around armour. | landing dust | | `environment` | Lava, spikes, acid: the world itself (`SecondWind.Trap`). Goes around armour. | red spikes | ### Death styles (`deathStyle`) | id | what happens | |---|---| | `instant` | Back at a spawn point straight away. | | `timed` | Back at a spawn point after `respawnDelay` seconds, with a MatchFlow countdown on screen. | | `wave` | Everyone who died comes back together on the next wave, every `Rules.waveInterval` seconds. | | `ragdoll` | The body is flung and tumbles limp, then respawns after `respawnDelay`. | | `dissolve` | The body sinks and dissolves into sparks, then respawns after `respawnDelay`. | | `spectate` | Stays dead and watches a living player until the round ends (`HK.endRound()`, a MatchFlow round ending, or `Rules.autoEndRound`). | | `remove` | Gone for good: for breakable props and one-shot enemies. | | `stay` | Stays dead until a script calls `HK.revive`. | ### Presets (`preset`) | id | model | death style | feed | friendly fire | |---|---|---|---|---| | `arcadeShooter` | hitPoints | instant | pixel | off | | `heroShooter` | shield (150 HP + 75 shield) | timed (5 s) | scifi | off | | `adventureHearts` | hearts (5) | dissolve | fantasy | off | | `roguelikeLives` | lives (3 × 40 HP) | ragdoll | pixel | off | | `coopRevive` | downed (20 s bleed-out) | wave | minimal | off | | `battleRoyale` | armor | spectate | minimal | on | | `partyBrawl` | hitPoints, huge knockback | ragdoll | cartoon | on | ### Kill feed looks (`feedLook`) `minimal`, `scifi`, `fantasy`, `cartoon`, `pixel`. Rows read like "Nova burned Kai" or "Kai was killed by Lava". ## Reference ### How settings resolve For each entity, each value is taken from the first of these that sets it: 1. The entity's own `Vitals` fields. A `model` or `deathStyle` of `auto` means "not set". 2. The entity's own `preset`. 3. For player bodies only: the world `Rules` (`playerModel`, `playerDeathStyle`, and the `preset`'s tuning). 4. For everything else: `hitPoints` and `Rules.otherDeathStyle`. `HK.config(target)` returns the resolved result. A model switch keeps the current health fraction. ### `SecondWind.api` (`local HK = require("SecondWind.api")`) Every target argument accepts an entity, a component or an entity id. | call | what it does | |---|---| | `HK.damage(target, amount, opts?) -> ok, reason` | Hurt a target. opts: `by`, `type`, `team`, `origin {x,y,z}`, `knockback` (m/s), `crit`, `dot`, `label` ("Lava"), `ignoreInvulnerability`, `status` (false = no burn/poison/chill). | | `HK.heal(target, amount, opts?) -> ok, reason` | Restore health. Hearts round up to half hearts. opts: `by`. | | `HK.kill(target, opts?) -> ok, reason` | Kill outright, skipping lives and downed. opts: `by`, `type`. | | `HK.base() -> Lifeline` | The Lifeline API SecondWind is built on (spawn points, the respawn picker, the local avatar). A kit built on SecondWind reaches Lifeline through this, so it depends on SecondWind alone. | | `HK.revive(target, opts?) -> ok, reason` | Pick a downed target up, or respawn a dead one now. | | `HK.explode(pos, opts?) -> count` | Explosion with falloff and knockback. opts: `radius` (5), `damage` (60), `by`, `team`, `knockback` (10), `minFalloff` (0.2). | | `HK.attach(entity, settings?) -> Vitals` | Add Lifeline.Health and SecondWind.Vitals with these settings. Use it in a build or on a freshly spawned entity. | | `HK.configure(target, settings) -> ok, reason` | Change any Vitals settings at runtime. | | `HK.setModel(target, model)` / `HK.setDeathStyle(target, style)` | Switch one setting. Pass `"auto"` to follow the preset or the rules again. | | `HK.applyPreset(name, target?)` | With no target, sets the world preset. With a target, sets that entity's own preset. | | `HK.setRules(t) -> ok, reason` | Change world rules, e.g. `{ friendlyFire = true }`. | | `HK.endRound()` | End the round: spectators come back. | | `HK.state(target)` | Snapshot in the terms of its model: `health, maxHealth, fraction, shield, maxShield, armor, maxArmor, hearts, heartsLeft, lives, livesLeft, downed, bleedLeft, reviveProgress, dead, deaths, respawnIn, dyingStyle, burning, poisonStacks, chilled, model, deathStyle, preset, team, name`. | | `HK.isAlive(target)` / `HK.isDowned(target)` | Booleans. A downed target counts as alive. | | `HK.config(target)` | The resolved settings (model, deathStyle, preset, all tuning). | | `HK.get(target)` / `HK.lifeline(target)` / `HK.all()` | The Vitals, the Lifeline.Health underneath, and every Vitals keyed by id. | | `HK.rules()` / `HK.ruleValues()` | The Rules component, and its values as a table (defaults when there is no Rules entity). | | `HK.nameOf(target)` / `HK.isPlayer(id)` / `HK.idOf(x)` | Display name, player-body test, and id normaliser. | | `HK.on(event, fn) -> conn` | Listen to an event on this peer (`"*"` = all). `conn:Disconnect()` stops it. | | `HK.killFeed()` | Recent kill feed entries on this peer. | | `HK.setDamageFilter(fn?)` | `fn(vitals, amount, info) -> amount`, run on the owner after team checks. Return 0 to cancel. | | `HK.catalog()` | Every model, damage type, death style, preset, feed look and event, plus `version` and `vocabulary`. Every entry carries its labels. | | `HK.find(query?) -> { entry }` | Catalog entries matching labels: `kind`, `family`, `genre`, `style`, `hasLook`, `id`. Each takes one value or a list. | | `HK.vocabulary()` | The words the labels use: kinds, families per kind, genres and styles. | | `HK.syncReport()` | How health sync is doing on this peer: `totals` (`sent`, `asked`, `served`, `resyncs`, `snapshots`, `evtSent`, `evtBatched`), the entities this peer `owned` and the ones it `watched` (in sync, seconds off, latest snapshot). | | `HK.VERSION`, `HK.HEALTH`, `HK.RULES`, `HK.logic` | The version string, the Vitals and Rules component assets, and the pure rules maths. | ### Events (`HK.on`) `damaged`, `healed`, `blocked` (reason: immune, friendly, self, armor, dead), `lifeLost`, `downed`, `revived`, `died`, `killed` (a kill feed entry: `killer, killerName, victim, victimName, type, text`), `respawned`, `statusApplied`, `chained`, `exploded`, `wave`, `roundEnded`. They fire on every peer. ### `SecondWind.Vitals` component Settings: `model`, `deathStyle`, `preset`, `team`, `displayName`, `barStyle`, `startFull`, `invulnerable`, `fallDamage`, `canRevive`. Tuning: `maxHealth` 100, `regenRate` 0, `maxShield` 50, `shieldRegenRate` 20, `shieldRegenDelay` 3, `maxArmor` 50, `armorAbsorb` 0.66, `hearts` 3, `lives` 3, `lifeHealth` 30, `bleedOutTime` 15, `reviveTime` 3, `reviveRadius` 2, `reviveHealth` 0.3, `respawnDelay` 4, `invulnerability` 0.5 (i-frames after a hit), `knockbackScale` 1. Read-only synced state: `armor`, `livesLeft`, `downed`, `bleedLeft`, `reviveProgress`, `reviver`, `respawnIn`, `dyingStyle`, `burning`, `poisonStacks`, `chilled`, `activeModel`, `activeStyle`, `activePreset`, `hitSeq`, `hitType`, `hitAmount` (the last hit, for its effect), `changeSeq` (bumped on every health change). Methods: `damage(amount, opts)`, `heal(amount, opts)`, `kill(opts)`, `revive(opts)`. It needs `Lifeline.Health` on the same entity; `awake` adds it when missing. ### `SecondWind.Rules` component (one per scene, on a synced entity) `preset` (applied when the Rules starts, to the fields still at their defaults, and again whenever it changes), `friendlyFire` (off), `selfDamage` (on), `playerModel` (hitPoints), `playerDeathStyle` (timed), `otherDeathStyle` (timed), `feedLook` (minimal), `waveInterval` 10, `autoEndRound` (on), `matchEntity` ("Match", a MatchFlow entity whose round end ends the SecondWind round), `maxRemoteDamage` 1000, `fallSafeSpeed` 10, `fallDamagePerSpeed` 7, `allowClientConfig` (off). Read-only: `waveIn`, `waveSeq`, `roundSeq`. ### `SecondWind.HUD` component (per peer, local) `feedLook` (`rules` follows Rules.feedLook), `showFeed`, `maxFeed` 5, `feedTime` 6, `showDeathScreen`, `showStatus`, `showDownedMarkers`, `countdownStyle` (any MatchFlow countdown style; default `bold`), `spectateSwitch` 8, `addLifelineHUD`, `autoBarStyle`. Method: `nextTarget()` switches the spectated player. ### `SecondWind.Trap` component A box volume that hurts what enters it: `damageType`, `label`, `amount`, `mode` (`perSecond` | `onEnter`), `interval`, `sizeX/Y/Z`, `knockback`, `team`, `by`, `playersOnly`, `active`. It runs on the authority of each victim, so put it on any entity, synced or not. ### Other modules - `SecondWind.catalog`: the data behind `HK.catalog()`. - `SecondWind.logic`: pure maths (pools, armour and shield split, falloff, fall damage, team rule, feed text). - `SecondWind.feed`: `render(look, entries, opts)` for your own UI. - `SecondWind.fx`: `burst(type, pos, amount)` hit effects. ### Multiplayer - **Authority:** each health is owned by the peer that owns its entity. A player's body belongs to that player, and synced world entities belong to the host. Only the owner changes health. All state is synced fields, so every peer sees the same health, deaths and respawns. - **Remote calls:** `HK.damage` on a target you don't own sends a request to its owner. The owner checks that you own the attacker you named, applies team and friendly-fire rules, and caps the amount at `maxRemoteDamage`. - **Admin calls:** `configure`, `kill`, `revive` and `endRound` from another peer are refused unless that peer owns the Rules entity or `allowClientConfig` is on. - **Events:** effects and events run on every peer. Events for other peers leave in batches on `healthKit:evts`, at most one message every 0.05 s, in the order they were raised; `healthKit:evt` messages from 1.1.0 peers are still received. Hit effects are drawn on the next frame from a queue, and each hit is drawn once per peer however it arrives (event or synced `hitSeq`). - **State snapshots:** the owner sends the full health state on the `healthKit:state` channel. It sends right away on every death, respawn, revive, life lost and knock-down, then again after 0.5 s and 2 s. It also sends after changes (at most once a second for players, every 3 s for others) and every 5 s regardless. Snapshots are batched, about 2 to 3 messages a second for a busy scene. A peer whose fields disagree with the last snapshot for over 0.5 s asks for a fresh one on `healthKit:resync`. All the kit's channels are registered when the kit loads; you do not call them yourself. ### Tests The `SecondWind.secondwind` test suite has 108 tests covering every public call: catalog labels and filtering, hit effects reaching peers, fall damage around death and respawn, health sync, event batching, the README's install step and first example, the package description, the 1.2.0 rename (new names, same guid, no old requires left, channels kept), and 1.3.0's starting preset, kill feed and guides (both guides ship in the package, the arena guide's settings exist on the components it sets them on, and no long dash in any file of the package, code included), the 1.4.0 health pools, and 1.4.3's checks that every file, the suite included, loads the kit with `~.` from wherever the package sits. Run it with `tools.use("tests", "run", { suite = "secondwind" })`. ## Known limits These are the open issues that still touch SecondWind: - **barsKit 1.4.0 installed on its own stops a new world's Play** (#22781 again). Its test suite loads SecondWind by a long `deps.` name that does not resolve once SecondWind sits at the top of the world, and when barsKit is installed alone its looks module's long `deps.` name for Lifeline does not resolve either. This is in barsKit, not SecondWind: forced past the error, its bars read SecondWind 1.4.3 health correctly. markersKit brings barsKit 1.3.1 with it, which plays, so the arena guide installs SecondWind and then markersKit. - **#22781: an error in an installed package's tests stops the installing world's Play** (and its publish), and the editor reports it as the world's own content. That is how 1.4.0's test suite stopped fresh installs. 1.4.3's suite passes the strict check wherever it is installed, and its own tests fail if a file loads the kit in a way that could break this again. If you change the suite in your copy, keep its requires on `~.`. - **#19258: ZeroMind's description of SecondWind can lag one release behind** for a while after a release is pushed. The package itself, this README and `package.yaml` are current. - **Message rate.** Lifeline, which the kit builds on and does not change, sends one `lifeline:evt` message for every hit, so the owner of many bodies taking damage at once still sends at least one message per hit. A peer with a low frame rate, such as a browser tab at 10 to 15 fps, drains those messages slowly, and everything sent after them waits behind them. The kit's own events are batched. Keep the number of bodies taking damage at the same moment modest, or only run them near players, as the showcase gallery does. - **#20750: frame rate in a web browser.** The kit uses only cross-platform engine APIs. The first example works in a browser tab (checked with a person on 1.1.2's code: the lava set the player on fire, the bar dropped and the dummy took damage), but plays choppily there, even in that small scene. On the native engine the same scene runs at about 19 ms a frame, of which the kit's components take about 0.5 ms; most of the rest is UI drawing, the built-in character controller and rendering. - **#20946: the web build can't be checked from an agent's engine.** 1.3.0 was checked on the native engine only. The earlier browser checks (1.1.0 to 1.1.2) were done live with a person in a browser tab. - **#14448: two engines signed in to one account collide as one player.** Test two players with two accounts. 1.3.0's two-player check ran in one engine, with a second player body beside the real one: one player knocked the other out, the kill feed credited the right player, the respawn came 3 s later at a spawn point with full health and shield, and in 23 samples the owner's health and shield matched the synced values every other peer reads. - **Tower freeze, seen once in a browser.** During a two-player test, a player in a web browser walked off the gallery's JUMP OFF platform and stayed hanging in the air, unable to move, until knocked out. It was not reproduced on the native engine, where the same walk falls and takes fall damage. Nothing in the kit was found to cause it: the kit only moves a player's body when it respawns. ## Version history - **1.4.6**: `died` and `killed` are heard once per death on every peer, not twice on peers that briefly hold a dying entity; two new tests (108). - **1.4.5**: Lifeline 1.0.4 and the current MatchFlow; no code changed. - **1.4.4**: The arena guide installs SecondWind and then markersKit (which brings barsKit 1.3.1) instead of barsKit 1.4.0, whose own test suite stops a new world's Play; the how-to guide and Known limits say what was checked with each kit on 1.4.3. No code change. - **1.4.3**: The test suite loads the kit with `~.` like the rest of the package and reads its files from wherever the package sits, so a fresh install plays, publishes and passes its tests (checked from ZeroMind in a new world, Play twice, the suite twice); five new tests guard every file's loads, the pool's rules and the version (106). README Known limits names only open issues; the how-to guide covers health pools; the package description and the world listing name the version. - **1.4.2**: `SecondWind.pool` requires `~.logic` again (the 1.4.0 merge had rewritten it to a `/source/...` path, so the pool failed wherever SecondWind is installed as a dependency); the suite's catalog and pool requires restored the same way. - **1.4.0**: `SecondWind.pool`, health for crowds with no component per entity (see What's new in 1.4.0). Four new tests (101). - **1.3.1**: No long dashes in any file of the package, and the test for them reads the code too; the showcase gallery in the Second Wind world rebuilt so every dummy shows its own model, death style and name, and the sign the current version. No change to how the kit behaves. See [What's new in 1.3.1](#whats-new-in-131). - **1.3.0**: One-call install; two guides in the package; a preset set on the Rules when it is created applies its model, death style, feed look and friendly fire; the kill feed tells two players with the same name apart; Known limits lists only open issues. See [What's new in 1.3.0](#whats-new-in-130). - **1.2.0**: healthKit became **SecondWind**, with the same guid (`5da0a53c-5953-4adc-80fb-f5afb02f6568`). The require line is `local HK = require("SecondWind.api")`; the components are `SecondWind.Vitals`, `SecondWind.Rules`, `SecondWind.HUD` and `SecondWind.Trap`, the modules `SecondWind.catalog`, `SecondWind.logic`, `SecondWind.feed` and `SecondWind.fx`, and the test suite `secondwind`. Upgrading from 1.1.x: change `healthKit.` to `SecondWind.` in your `require` and `asset.resolve` lines. The network channels (`healthKit:evts`, `healthKit:state` and the rest) and the HUD's screen id `healthkit_hud` kept their names, so nothing on the wire changed. The package description became a store listing. - **1.1.4**: The first example works as pasted: its dummy stands in the edge of the lava, on the ground, and an orange slab shows where the lava is. The world opens in the gallery again. The package description counts eight death styles and names `Vitals`. - **1.1.3**: Step 1 became two install calls, as a workaround for an engine install problem that has since been fixed; 1.3.0 goes back to one call. - **1.1.2**: Step 1 named Lifeline and MatchFlow as installs of their own (also a workaround, also gone in 1.3.0). Tests for the install instructions. - **1.1.1**: Events for other peers leave in batches (one `healthKit:evts` message per 0.05 s, in order); `HK.syncReport().totals` counts `evtSent` and `evtBatched`. A lighter showcase gallery: dummies and damage stations only run near a player, and the host sends about 12 to 14 messages a second instead of about 46. - **1.1.0**: A labelled catalog (`HK.find`, `HK.vocabulary`); hit effects drawn on every player's screen, also from the synced `hitSeq`, `hitType` and `hitAmount`; full health snapshots on every death, respawn, revive, life lost and knock-down, with resyncs; fall tracking reset on death and respawn, so a fall death no longer charges a second fall hit; gallery dummies without a `{PlayerName}` placeholder. - **1.0.0**: First release: six health models, eight damage types, eight death styles, teams and friendly fire, a kill feed in five looks, traps and genre presets.
▲ 2↓ import
▣
module · born here
❒asset
# projectileKit.vec Small vector and quaternion maths on plain `{ x, y, z }` arrays (`{ [1], [2], [3] }`). Every function is pure (no engine calls), so every peer computes the same numbers and the tests can check them directly. Used by `projectileKit.motion`, `projectileKit.render`, `projectileKit.api` and by turretsKit's aiming and targeting code. Require it as `~.vec` from inside the package. ## Type - `export type Vec = { number }`: a three-element array `{ x, y, z }`. ## Functions Reading positions - `of(v: any): Vec?`: reads a position from an array, a keyed table `{ x, y, z }`, a `vector` or an entity position proxy; returns a fresh array, or `nil` when it is not a position. Arithmetic (all return new arrays) - `add(a, b): Vec`, `sub(a, b): Vec`, `scale(a, k): Vec` - `dot(a, b): number`, `cross(a, b): Vec` - `len(a): number`, `dist(a, b): number`, `flatDist(a, b): number` (ignores Y) - `lerp(a, b, t): Vec` - `norm(a): Vec`: unit vector; a near-zero vector returns `{ 0, 0, 1 }`. - `segmentDistance(p, a, b): (number, number)`: distance from `p` to segment `a-b`, and the segment parameter (0..1) of the closest point. Angles and quaternions (quaternions are `{ x, y, z, w }`, yaw 0 faces +Z, positive pitch is up) - `yawPitchQuat(yaw, pitch): { number }`: yaw about +Y, then pitch tilting local +Z upward. - `lookQuat(dir: Vec): { number }`: rotation turning local +Z to point along `dir`. - `axisQuat(axis: Vec, angle: number): { number }`: rotation of `angle` about a unit axis. - `rotate(q, v: Vec): Vec`: rotates `v` by `q`. - `yawPitchOf(dir: Vec): (number, number)`: yaw and pitch of a direction, in radians. - `dirOf(yaw, pitch): Vec`: unit direction for a yaw and an upward pitch. - `wrap(a): number`: wraps an angle to (-pi, pi]. Determinism - `rng(seed: number): () -> number`: a seeded random stream returning numbers in [0, 1); the same seed gives the same sequence on every peer.
▲ 0↑ born
▣
module · pulled in
❒asset
# api The one interface to SecondWind: `local HK = require("SecondWind.api")`. - **Damage:** `damage`, `heal`, `kill`, `revive`, `explode`. - **Configure:** `attach`, `configure`, `setModel`, `setDeathStyle`, `applyPreset`, `setRules`, `endRound`. - **Query:** `state`, `isAlive`, `isDowned`, `config`, `get`, `lifeline`, `all`, `rules`, `ruleValues`, `nameOf`, `isPlayer`, `catalog`, `killFeed`. - **Hooks:** `on` (events) and `setDamageFilter`. Calls on a target this peer does not own are sent to its owner, who checks them (attacker ownership, teams, the damage cap, config permission) before applying them. The package README lists every argument.
▲ 0↓ import
▣
module · born here
❒asset
# turretsKit.targets What a turret can shoot at, gathered at most every `REFRESH` (0.1 s) for every turret on this peer. The `turretsKit.Turret` component reads it in its scan and for splash, spray, hitscan and chain hits; `turretsKit.combat` uses it for walls, clouds and slows. `turretsKit.api` re-exports `add`, `remove` and `setProgress` as `addTarget`, `removeTarget` and `setProgress`. ## Where candidates come from 1. Anything with SecondWind health (`SecondWind.Vitals`) that is alive: enemies, dummies, breakable props. Players count only for turrets with `targetPlayers` on. 2. spawnerKit enemies (`spawnerKit.Enemy`) are read for their path progress; enemies waiting in spawnerKit's pool (not `active`) are skipped. 3. Targets a game registers with `add`, with its own team, progress and health. "How far along the path" (used by `first`/`last`) is, in order: the `setProgress` function; a target's own `progress` function; a spawnerKit path enemy's place on its route (0 at the start, 1 at the end); otherwise how long this peer has seen it. ## Candidate record `{ id, pos, health, maxHealth, team, player, enemy, progress, vel? }`: `vel` is estimated from the last position (dropped above 30 m/s, a teleport). Custom targets without health carry `custom = true`. ## Functions - `add(target: any, opts: any?)`: registers an entity (or id) as a target, or gives a health target its own data: `opts = { team, progress = fn(id) -> 0..1, health = fn(id) -> number }`. - `remove(target: any)`: stops treating it as a custom target. - `setProgress(fn: any)`: `fn(id, pos) -> number` (bigger = further along) or `nil` to fall back, for games with their own movers. - `enemyOf(e: any): any`: the entity's `spawnerKit.Enemy` component, or `nil`. - `all(force: boolean?): { any }`: every target this tick (`force` refreshes now). - `forTeam(team: string, targetPlayers: boolean): { any }`: fresh copies of the targets not on `team` (players only when `targetPlayers`). - `get(id: string): any`: one target's record this tick, or `nil`. - `clearLine(from, to, targetId: string?, ignore: { string }?): boolean`: whether no collider stands between the two points (a physics raycast; models without colliders never block). - `reset()`: forgets every cached target (tests use it between cases).
▲ 0↑ born
▣
module · born here
❒asset
# turretsKit.net Who is in charge of a turret, and the three multiplayer channels the kit talks on. Used by `turretsKit.api` (commands, events, the per-frame flush), `turretsKit.combat` and the `turretsKit.Turret` component (ownership, shot records). ## Channels | Field | Channel | Carries | |---|---|---| | `FX` | `turretsKit:fx` | Shots, bolts and clouds the turret's owner fired, batched into one message a frame, so every other peer draws the same shot on the same path. Damage is never in it. | | `CMD` | `turretsKit:cmd` | Setting changes, upgrades and sells asked for on a peer that is not in charge, carried out by the one that is. | | `EVT` | `turretsKit:evt` | built / upgraded / sold / changed events, so every peer's listeners hear them. | In charge of a turret = the owner of its synced entity, or the room host while nobody owns it (spawnerKit and aiKit use the same rule), or this peer when offline. Subscriptions are remade whenever the engine mode or the room changes; older ones go quiet (they check a generation number), so no message is handled twice. Nothing is sent when no other peer is in the room. ## Functions - `online(): boolean`: whether this engine is in a multiplayer room. - `owns(e: any): boolean`: whether this peer is in charge of an entity (its owner; the host while nobody owns it; any unsynced entity; always when offline). - `othersHere(): boolean`: whether any other peer is in the room. - `handle(kind: string, fn: (number, any) -> ())`: sets the handler for `"fx"` (called once per record), `"cmd"` or `"evt"`: `fn(fromPeer, payload)`. - `subscribe()`: (re)subscribes to the channels if the mode or room changed. - `queueFx(rec: any)`: queues a shot record for the other peers. - `flush()`: sends queued shot records as one message and re-subscribes if needed. Runs once a frame; extra calls in the same frame do nothing. - `sendCmd(cmd: any)`: asks the peer in charge to do something. - `sendEvt(evt: any)`: tells every other peer about an event. - `stats(): any`: what this peer has sent: `{ fx, records, cmd, evt }`.
▲ 0↑ born
❒
package · born here
❒asset
# projectileKit Pooled projectiles, beams, lightning arcs and puffs for Zero. Bullets fly straight, shells lob on a ballistic arc that lands exactly where you aim (over walls), and missiles home on a moving target. Lasers are continuous beams, lightning is jagged arcs, and puffs, bursts and rings cover flames, frost, poison clouds, explosions and muzzle flashes. Everything is drawn from **pools of reused entities**, moved with a few batched transform writes a frame. Nothing is spawned or destroyed per shot, so hundreds of shots in the air stay smooth on desktop, web and phones. It is the projectile layer under [turretsKit](../turretsKit.package/README.md), and it works on its own for any weapon, trap or spell. ## Install `zeromind_install` the `projectileKit` package, or install turretsKit, which brings it along. It needs nothing else. ## Use it ```lua local PK = require("projectileKit.api") -- a tracer that hits whatever stands on its line PK.fire({ kind = "bullet", from = muzzle, target = enemy, aimHeight = 0.9, speed = 70, look = "tracer", onHit = function(shot, hit) if hit.target then print("hit", hit.target) end end }) -- a mortar shell that peaks 8 m up and bursts where it lands PK.fire({ kind = "shell", from = muzzle, to = { 10, 0, 20 }, arc = 8, look = "shell", impact = "blast", onHit = function(shot, hit) print("landed at", hit.pos[1], hit.pos[3]) end }) -- a homing missile that climbs, then chases its target, leaving smoke PK.fire({ kind = "missile", from = muzzle, target = enemy, speed = 22, turnRate = 160, launchDir = { 0, 1, 0.3 }, look = "missile", trail = "smoke", impact = "blast" }) -- a laser: call every frame while it fires; it fades out on its own when you stop PK.beam("laser-1", muzzle, enemyChest, "laserRed", 1) -- one lightning bolt, a flame puff and an explosion PK.arc(from, to, { look = "arcCyan", life = 0.2 }) PK.puff(pos, { look = "flame", vel = { 0, 1, 5 }, life = 0.5 }) PK.burst(pos, { look = "blast", size = 3 }) ``` Positions can be `{ x, y, z }` lists, `{ x =, y =, z = }` tables, vectors or an entity's `position`. A `target` can be an entity or an entity id. The kit spawns its own runner entity the first time anything is fired, so there is no component to add. In edit mode or in tests, drive it by hand with `PK.step(dt)`. ### `PK.fire(spec)` | field | meaning | |---|---| | `kind` | `bullet` (straight), `shell` (ballistic arc) or `missile` (homing) | | `from`, `to` | start, and aim point (defaults to the target's position) | | `target` | entity or id: bullets and missiles hit it on contact, missiles chase it | | `speed` | m/s (bullets and missiles) | | `arc`, `gravity` | shells: metres above the higher end at the peak; m/s² | | `turnRate` | missiles: degrees per second. The turn tightens the longer it flies, so a missile never orbits | | `radius`, `aimHeight` | contact distance; height added to the target's position | | `look`, `size` | which pooled look draws it, and a scale | | `trail`, `trailEvery` | a puff look dropped behind it | | `impact`, `impactSize` | a burst look where it ends | | `draw = false` | simulate without drawing | | `logic = false` | draw without calling `onHit` (for copies of a shot on other players' machines) | | `onHit(shot, hit)` | `hit = { pos, target, reason = "hit" | "arrive" | "expire", aimedAt }` | | `data` | anything; kept on the shot for `onHit` | ### Looks 43 looks ship in `projectileKit.looks`: tracers (yellow, red, blue), crossbow bolt, foam dart, pellet, steel shell, cannonball, catapult stone, rubber ball, plasma ball, missile, firework rocket, toy rocket, red/green/blue lasers, arcane ray, candy ray, sniper trail, cyan/violet/yellow lightning, flame, frost shard and mist, poison puffs, smoke, sparks, confetti, bubbles, explosion and plasma burst, shock/frost/poison/boost rings and muzzle flash. `PK.lookNames()` lists them. Add your own: ```lua PK.defineLook("greenTracer", { color = { 0.3, 1, 0.4 } }, "tracer") -- copy tracer, change the colour PK.defineLook("arrow", { mesh = "cube", color = { 0.5, 0.35, 0.2 }, size = { 0.05, 0.05, 0.8 }, cap = 80 }) ``` A look is a built-in mesh (`cube`, `sphere`, `cylinder`, `octahedron`, `torus`, `cone`, `capsule`), `glow` or `metal` or plain plastic, a colour, a size, an optional `stretch` (tracers lengthen with speed) and a `cap` (most drawn at once). ## The budget, and why it stays smooth - **Shots are data.** Every shot, puff and bolt is a plain table simulated in one loop. Finished tables are recycled, and so are shots that land over budget or are cleared mid-flight. - **No garbage per frame.** A step moves every shot in place, draws it with plain numbers (`render.drawRaw`) and reads target positions into one reused table. Steady state with 300 or 1,000 shots in flight allocates nothing, and a test checks it. Measured on desktop: 300 shots in flight cost 0.2 ms a step, 600 cost 0.3 ms, 1,000 cost 1.35 ms. A shot over its look's drawing cap skips the drawing maths entirely. - **Drawing is pooled.** Each look owns a pool of entities made once. Each frame, `render.flush` writes all their positions, rotations and scales in three batched calls per look, through typed buffers. Unused pool members are parked at zero scale; nothing toggles visibility or spawns per shot. Measured: 300 pooled entities moved this way cost about 0.07 ms, while 300 per-entity visibility toggles cost about 8 ms. - **Pools grow gently.** At most `spawnPerFrame` new pool entities a frame, up to each look's `cap` and the global `maxVisible`. `PK.prewarm(look, n)` makes them ahead of time. - **Over budget, nothing is lost.** Past `maxShots`, a new shot lands at once (its `onHit` still fires). Past `maxEffects`, the oldest cosmetic effect gives way. | preset | `maxShots` (simulated) | `maxEffects` | `maxVisible` (drawn) | `spawnPerFrame` | |---|---|---|---|---| | `desktop` | 1500 | 900 | 600 | 12 | | `web` | 1000 | 500 | 360 | 8 | | `phone` | 600 | 260 | 220 | 6 | `PK.setBudget("phone")` picks a preset, or pass a table with any of the four numbers. `PK.suggestedBudget()` names the preset that suits the machine, from the platform the engine reports (`engine.platform`) and the viewport size: `phone` on Android or when the short side of the screen is under 700 px, `web` in a browser (`engine.platform == "browser"`), else `desktop` (the desktop app). `PK.budgetFor(platform, width, height)` is the same rule for any platform and size, so a game or a test can see what a browser or a phone would get. `PK.stats()` reads it all back: shots flying, effects, beams, fired/hit/arrived/expired, instant landings, shot tables reused vs made, and pool sizes. ## Multiplayer projectileKit draws locally and sends nothing. A game that wants every player to see a shot sends the shot's numbers to the other peers and fires it there with `logic = false`, so only one machine deals the damage. turretsKit does exactly that, batching every turret's shots into one message a frame. The flight maths is deterministic (`projectileKit.motion` has no clock), so the same numbers fly the same path on every machine. ## Reference - `projectileKit.api`: `fire`, `kill`, `beam`, `endBeam`, `hasBeam`, `arc`, `puff`, `burst`, `ring`, `step`, `setBudget`, `budget`, `suggestedBudget`, `budgetFor`, `stats`, `resetStats`, `prewarm`, `defineLook`, `lookNames`, `clear`, `BUDGETS`, `VERSION` - `projectileKit.motion`: `solveBallistic`, `lead`, `launch`, `step`, `predict` (pure maths) - `projectileKit.vec`: small vector and quaternion helpers on `{ x, y, z }` lists - `projectileKit.looks`, `projectileKit.render`: the look catalogue and the pools - `projectileKit.Runner`: the component that ticks the loop (spawned for you) ## Tests `tools.use("tests", "run", { suites = { "projectileKit" } })` in edit mode runs 14 tests: vector helpers, shells landing on target, bullets hitting, missiles homing on a moving target from awkward launch angles, lead, `onHit` once per shot, shot-table recycling (including over budget and after a clear), a step making no garbage, over-budget landing, pool reuse, budget presets, the automatic budget per platform (browser → web, Android or small screen → phone, desktop app → desktop), beams and effects expiring, and `hitTest` / `kill` ending shots early. ## Version 1.1.0 adds two small, general hooks and changes nothing else: a shot spec's `hitTest(shot, dt)` callback (checked after each step; return a target to end the shot as a hit on it, so a bullet can hit any of many targets, e.g. every player in a bullet-hell volley) and `PK.kill(shot, reason)` to end a shot early. Contributed by bulletPatternsKit. 1.0.2, published with turretsKit 2.1.4 from the Bastion Works world. 1.0.2 changes no code: its library description now says what you get and how to install it, and it is built on the engine library `ab1aa41`. 1.0.1 changed no code either: its docs and code comments no longer use long dashes, and its version number moved because ZeroMind publishes one content under each version. Release history, honestly: there were no version bumps, but 1.0.0 was published several times on 2026-10-23, always under the number 1.0.0. The changes that reached it were the first build (around 17:01 UTC), the performance pass that made the shot loop garbage-free (around 17:55), and the fix that makes the automatic budget recognise a browser (around 21:45). The browser fix had two parts: the engine reports `"browser"`, which the old check (looking for "web") never matched, and the viewport size arrives as one `{ width, height }` table. Before it, browsers got the desktop budget and small screens never got the phone budget. Install the latest. 1.0.1 was published once, on 2026-10-31, with turretsKit 2.1.1. 1.0.2 was published once, on 2026-10-31, with turretsKit 2.1.4.
▲ 0↑ born
❒
package · born here
❒asset
# turretsKit Towers, turrets and targeting for tower defense, base defense and sentry-gun games. Put **one Turret part** on an entity and give it two names: **which turret it is** and **how it picks targets**. Change either name while it fires and it changes on the spot, with no other code. - **12 turrets, all data**: machine gun, cannon, mortar, laser, tesla, frost, poison cloud, missile, sniper, flamethrower, support beacon and wall. A designer tweaks or adds one by editing a `.data` file. - **5 targeting modes**: `first` (furthest along the path), `last`, `nearest`, `strongest`, `weakest`. You can add your own. - **Real turret feel**: every turret has left/right and up/down turn limits and turn speeds. Anything outside its arc is never picked. It sweeps when idle, tracks, leads moving targets and holds its aim for a moment when a target is lost (the brain is a [Watchful Minds aiKit](https://origozero.ai) state machine shaped like aiKit's own turret). - **3 upgrade tiers per turret** that change the model and every number, each with a cost. Selling pays back a sell value through a hook your money system listens to. Every number reads back. - **3 looks**: sci-fi, medieval fantasy and cartoon toy. One call swaps the whole world, or swap a single turret. - **Built for crowds**: projectiles, beams and effects come from [projectileKit](../projectileKit.package/README.md) pools, and damage is batched, so many turrets firing into a big crowd stays smooth on web and phones. - **Multiplayer**: one machine decides each turret's target and deals its damage, so a hit lands once. Other players see that machine's targets, health and kill counts after a sync delay, which can be a second or more (see [Multiplayer](#multiplayer)). Health and damage come from **SecondWind** (burns, poison, chill, chain lightning, teams, kill feed). It works with **Wavecaller spawnerKit** enemies walking a path, and with **Gaugeworks barsKit** health bars. ## Install One install, one id, nothing else to install: ``` zeromind_install { guid: "fc8b64ab-27cc-4d1a-9746-a0f55ac9e442" } // turretsKit 2.1.4 ``` That brings everything turretsKit runs on, each kit from its own world: projectileKit for the pooled projectiles, Second Wind (health and damage, with the Lifeline and MatchFlow pieces it needs), Wavecaller spawnerKit (the enemy stream; turretsKit also reads its enemies' routes for `first` / `last`) and Watchful Minds aiKit (the turret brain's state machine and presets). **Use those kits by their own names.** Every kit the install brings is a package of your world, so your own scripts require it the plain way: ```lua local TK = require("turretsKit.api") local SK = require("spawnerKit.api") -- Wavecaller spawnerKit local HK = require("SecondWind.api") -- Second Wind local FSM = require("aiKit.fsm") -- Watchful Minds aiKit's state machine (and "aiKit.presets") ``` They are the very modules turretsKit runs on. `TK.kits` is still there as a shortcut to the same modules (`TK.kits.spawnerKit`, `TK.kits.SecondWind`, `TK.kits.aiKit.fsm` / `.presets`), so code written for 2.0.2 keeps working. Checked on 2026-10-31 (engine library `fe09783`, before the `ab1aa41` this release is built on), in a brand-new empty world with turretsKit as its only install: 711 files and 11 dependencies arrived with no problems, every kit answered to its own name, turretsKit's and projectileKit's 43 tests passed, and the quick start below ran exactly as written. That check was made with 2.1.0; 2.1.1 changes no code, only the docs, the guides and two numbers in the quick start (see Version). ### What it depends on, and which version turretsKit 2.1.4 was built and tested against exactly these versions. The *published version* column is the start of the content id ZeroMind installs (`zm status` shows the same short id for each install). *How it arrives* says what an install of turretsKit alone brings. | Package | From (world) | Version | Published version | Asset id | How it arrives | |---|---|---|---|---|---| | projectileKit | Bastion Works (this world) | 1.0.2 | the latest 1.0.2 | `0b2aaa66-56b2-4f3e-80f8-05f8a9f07d04` | the whole package, with turretsKit | | SecondWind | Second Wind (`7a497fbf…`) | 1.2.0 | `b4d0918` | `5da0a53c-5953-4adc-80fb-f5afb02f6568` | the whole package; `require("SecondWind.api")` | | spawnerKit | Wavecaller (`428a5541…`) | 1.0.0 | `049ac51` | `866b48e5-deed-4e7f-84a8-94ec29134c81` | the whole package; `require("spawnerKit.api")` | | aiKit | Watchful Minds (`1d574edc…`) | 1.1.0 | `a45e765` | `549ff927-79bc-4db2-b5b2-35d5f3fd59cb` | the whole package; `require("aiKit.fsm")`, `require("aiKit.presets")` | | navKit | Watchful Minds (`75ad3c13…`) | 1.2.1 | `3832dcf` | `286dd3bb-0744-4157-b9f0-c98cc03ee326` | the whole package, with aiKit | | Lifeline | Lifeline (`45f92606…`) | 1.0.1 | `c8e3fae` | `7b85ce05-3903-4374-b654-2d4ffea295a5` | the whole package, with Second Wind | | MatchFlow | Match Flow Kit (`40bc9b7f…`) | 1.1.0 | `4c6c52e` | `31cf13b4-df7d-4888-85e2-7947a7301614` | part of the package, with Second Wind and spawnerKit: the `MatchFlow` and `Countdown` components and most of its modules, but not its `api` module, so `require("MatchFlow.api")` answers "module not found" ([#22186](https://github.com/OrigoZero/zero/issues/22186)). Reach it through its component by name, `entity.find("Match").component.get("MatchFlow")`, as the tower defense guide does | | juiceKit | juiceKit (`46548c0c…`) | 1.2.2 | `be142e5` | `eed55f6d-afaf-4767-83c5-539ef91e0dc5` | the whole package, with spawnerKit | | barsKit (optional) | Gaugeworks (`d9f6c7f4…`) | 1.3.0 | `046996d` | `c154eb07-ce7c-48ca-8232-4ce1a8754214` | not brought; install it yourself for its health bars | | Zero engine library (`@builtin`) | the engine (`07158574…`) | branch `main`, pinned commit | `ab1aa41` | none | provided by the engine, plus pinned copies of two engine files a kit was published with (see Known limits) | Bastion Works itself has Second Wind, spawnerKit and the whole aiKit installed, each fresh from its own world, which is what lets an install of turretsKit bring each of them from its own world rather than from this one. Gaugeworks **barsKit** is optional (its health bars, see below). ## Three turrets shooting a stream of enemies, in five minutes Make a scene (or open your scene's `build.luau`) and use this as its build. It runs as written in a world where turretsKit is the only install: an endless stream of spawnerKit grunts and runners walks a path past a tesla coil, a cannon and a machine gun, in that order, and all three shoot from the first wave on (the tesla coil first, so it gets enemies before the others have thinned the stream). ```lua local TK = require("turretsKit.api") local SK = require("spawnerKit.api") -- Wavecaller spawnerKit, brought by turretsKit local HK = require("SecondWind.api") -- Second Wind, brought by turretsKit function content() -- ground and light local ground = entity.spawn("ground") ground.component.add("Model", { model = asset.resolve("@builtin::meshes.cube", "mesh"), material = asset.resolve("@builtin::materials.lit_checkerboard", "material") }) ground.component.add("BoxCollider", {}) ground.localPosition = { 0, -0.1, 8 } ground.localScale = { 60, 0.2, 40 } entity.spawn("sun").component.add("Light", { kind = "directional", intensity = 0.9, directionX = -0.3, directionY = -0.8, directionZ = 0.4 }) entity.spawn("sky").component.add("ProceduralSky", { timeOfDay = 15 }) -- SecondWind's health rules: one per scene, on a synced entity entity.spawnSynced("HealthRules").component.add(HK.RULES, {}) -- a path of eight points, left to right in front of the player for i = 1, 8 do local p = entity.spawn(`Path{i}`, { position = { -21 + i * 5, 0, 12 } }) SK.addSpawnPoint(p, { group = "Path", order = i, kind = "path" }) end -- an endless stream of spawnerKit enemies walking that path SK.addSpawner(entity.spawnSynced("Stream", { position = { -16, 0, 12 } }), { pattern = "path", points = "Path", effect = "none", curve = "flat", advance = "timer", maxAlive = 12, waveTable = { loop = true, waves = { { delay = 1, gap = 1.2, points = { "Path" }, enemies = { { kind = "grunt", count = 8 }, { kind = "runner", count = 4 } }, } } }, }) -- three turrets, each set up by two names: which turret, and how it picks targets local function turret(name: string, pos: { number }, kind: string, mode: string) TK.addTurret(entity.spawnSynced(name, { position = pos }), { def = kind, targeting = mode }) end turret("Gun", { 8, 0, 6 }, "machineGun", "first") turret("Cannon", { 0, 0, 6 }, "cannon", "strongest") turret("Tesla", { -8, 0, 6 }, "tesla", "nearest") -- the player local setups = entity.spawn("PlayerSetups") local prototype = entity.spawn("Player", { parent = setups }) prototype:setParticipation("PrototypeOnly") local body = entity.spawn("body", { parent = prototype }) body.component.add("Asset", { source = asset.resolve("@builtin::avatars.humanoid", "avatar") }) local rig = entity.spawn("CameraRig", { parent = prototype }) rig:setNetworkScope("OwnerOnly") rig.component.add("Camera", { behavior = asset.resolve("@builtin::controller.orbital_follow", "component") }) rig.localPosition = { 0, 2.6, -5 } rig.localRotation = { 0, -0.9961332, -0.0878564, 0 } prototype.component.add("PlayerPrototype", { body = body, camera = rig }) local start = entity.spawn("Start", { parent = entity.spawn("Spawns"), position = { 0, 0, -2 } }) start.component.add("PlayerSpawn", { prototype = prototype }) end ``` Press play. The enemies carry spawnerKit's own health bars. For Gaugeworks barsKit bars instead, set `healthBars = false` on the spawner and add a bar to each enemy as it spawns, in the scene's `entrypoint.luau`: ```lua local SK = require("spawnerKit.api") local BK = require("barsKit.api") function onLoad() SK.on("spawned", function(e) local id = if type(e) == "table" then (e.enemy or e.id) else e if type(id) == "table" then id = id.id end if type(id) == "string" and entity.exists(id) and BK.barOf(entity(id)) == nil then BK.bar(entity(id), { look = "overhead" }) end end) end ``` Now change things while it plays: ```lua local TK = require("turretsKit.api") local gun = entity.find("Gun") TK.set(gun, "def", "laser") -- it is a laser now, mid-fight (TK.setDef(gun, "laser") does the same) TK.setTargeting(gun, "weakest") -- and finishes off the weak ones TK.upgrade(gun) -- Mk II TK.setStyle("toy"); TK.setStyleAll("toy") -- every turret in the cartoon toy look print(TK.info(gun).stats.fireRate, TK.info(gun).costs.sell) ``` You can also set the same fields in the editor's inspector on the Turret component. ## The Turret part (`turretsKit.Turret`) Put it on a **synced** entity (`entity.spawnSynced`). `TK.addTurret(e, fields)` does that and validates the names. The entity's forward (+Z) is the turret's home facing, which its turn limits are measured from. | field | default | meaning | |---|---|---| | `def` | `machineGun` | which turret it is, by name (any turret type's `id`). Change this one field live to swap the turret | | `targeting` | `first` | how it picks: `first`, `last`, `nearest`, `strongest`, `weakest`. Change it live | | `tier` | 1 | upgrade tier 1 to 3: model and numbers | | `style` | `auto` | `scifi`, `medieval`, `toy`, or `auto` (the world default, `TK.setStyle`) | | `team` | `defenders` | SecondWind team. It never shoots its own team | | `targetPlayers` | false | also shoot players (sentry guns) | | `active` | true | off: it stands idle | | `label`, `note` | true, "" | floating label, two lines: the name, then tier · targeting mode (support: tier · its boost; wall: tier · health), plus an optional extra line. It stands a little toward the camera of the screen drawing it, so no part of the turret, in any look, covers its text | | `labelSize`, `labelLift`, `labelAt` | 1, 0, 0 | label size; extra height above the model; or a fixed height above the base (`labelAt` > 0), to line labels up in rows that never cross. See [Labels on any screen](#labels-on-any-screen) for phones held upright | | `showRange` | false | draw its range on the ground | | `target`, `state`, `aimYaw`, `aimPitch`, `kills` | | written by the machine in charge, read them anywhere | ## The twelve turrets | name | what it does | its special number per tier | |---|---|---| | `machineGun` | fast tracer bursts at one target; turns fast | bullets per burst 1 / 2 / 3 (barrels 1 / 2 / 4) | | `cannon` | heavy shell on a low arc, splash damage | splash radius 1.8 / 2.4 / 3.2 m | | `mortar` | lobs shells high over walls (no line of sight needed), minimum range 5 m | splash radius 2.5 / 3.2 / 4 m | | `laser` | continuous beam that ramps up while it holds one target | ramp ×1.5 / ×2 / ×3 | | `tesla` | lightning that jumps from enemy to enemy | chain jumps 2 / 4 / 6 | | `frost` | ice shards that slow everything they chill | slow 30 / 45 / 60 % | | `poison` | lobs a glob that leaves a toxic cloud: damage over time in an area | cloud damage 8 / 12 / 18 per s | | `missile` | homing missiles that climb and chase | missiles per salvo 1 / 2 / 4 | | `sniper` | long range, slow, huge hits that pierce through a line | enemies pierced 1 / 2 / 3 | | `flame` | short cone of fire that sets things burning | burn 4 / 6 / 9 per s | | `support` | never fires; turrets in its aura fire faster, hit harder, reach further (the strongest beacon counts) | fire-rate boost 15 / 25 / 40 % | | `wall` | never fires; blocks enemies that walk into it and soaks their damage, rebuilds after breaking | health 400 / 700 / 1100 (thorns from Mk II) | Every tier also raises fire rate, range and damage. `TK.types()` lists every type with its tags and every number of every tier (`TK.types("splash")` lists only the types tagged `splash`, see [Tags](#tags)); `TK.info(turret)` reads a placed turret's current numbers, costs, turn limits and aim. ### Adding or tweaking a turret Each turret is a `.data` file bound to the `turretsKit.turretType` contract (the kit's twelve are in `turretsKit.package/turrets/`). Copy one anywhere in your world, change its `id` and numbers, and a Turret can use it by that `id` at once. The contract's README explains every field. From code: ```lua TK.define("heavyGun", { label = "Heavy Gun", turn = { yawSpeed = 120, yawMin = -60, yawMax = 60 } }, "machineGun") ``` ## Targeting - `first` targets the enemy furthest along its path, `last` the one least far along. For spawnerKit path enemies the kit reads their place on the route. For your own movers, give it a number with `TK.setProgress(function(id, pos) return myProgress[id] end)`, or per target with `TK.addTarget(e, { progress = fn })`. Otherwise the enemy seen longest counts as furthest. - `nearest` is the closest enemy to the turret. `strongest` and `weakest` compare health plus shield. - Ties fall back to progress, then to the entity id, so every machine agrees. - Only candidates inside range (and outside the mortar's minimum range), inside the turn limits and in clear line of sight are picked. Mortars and poison throwers lob over walls, so they need no sight line and ignore the up/down limit. - A mode of your own: `TK.defineTargeting("lowestArmor", function(a, b) return armor(a.id) < armor(b.id) end, "Lowest armour", { "targeting", "armor" })`. The label and tags are optional. Targets are anything with SecondWind health on another team: spawnerKit enemies, aiKit characters, props, and players when `targetPlayers` is on. `TK.addTarget(e, { team, progress, health, layer, hidden })` adds something without SecondWind health. ### Layers (air and ground) and stealth Every target has a **layer**, `"ground"` or `"air"`, and can be **hidden** (stealthed). A turret type says which layers it can shoot and whether it can see hidden targets, with three optional fields in its `.data` file (or `TK.define`): | field | default | meaning | |---|---|---| | `hits` | `[]` (both) | the layers it shoots: `["ground"]`, `["air"]` or `["ground", "air"]`. Empty means both, so every turret written before layers existed shoots everything, as before. | | `detects` | `false` | it can see and shoot hidden targets. | | `detectRange` | `0` | how far it sees hidden targets, in metres; 0 = its whole range. A tier may set its own `detectRange`. | Where a target's layer and stealth come from: - **A hook**: `TK.setTargetInfo(function(id, cand) return { layer = "air", hidden = true, lift = 2.2 } end)`. Return nil to keep the defaults. `lift` raises the point turrets aim at and measure range to, for a flier drawn above its entity; `progress` (optional) replaces the path progress the kit worked out, which arrives as `cand.progress`. An enemy roster kit (such as creepsKit) installs this hook; `TK.setTargetInfo(nil)` removes it. - **Per target**: `TK.addTarget(e, { layer = "air", hidden = false })`. - **By default**: a spawnerKit enemy whose kind hovers (`hover > 0`, such as the sample `flyer`) is `"air"`, everything else `"ground"`, and nothing is hidden. What each attack does with them: - **Picking a target** (every targeting mode) skips layers the turret does not hit and hidden targets it cannot detect. A tracked target that turns hidden or moves out of the turret's layers is dropped at once. - **Chain lightning** only jumps to targets the turret could pick itself; a **sniper's pierce** only hurts those. - **Splash, clouds and flame cones** hurt every target in a layer the turret hits, **hidden ones included**: a blast needs no sight. That is how a game reveals stealthed enemies, by noticing they were hit. - **Walls** only block ground targets; fliers pass over them. None of the twelve turrets declares `hits` or `detects`, so they all shoot both layers and none detects. Make a ground-only cannon or a detecting sniper with one line each: ```lua TK.define("cannon", { hits = { "ground" } }, "cannon") TK.define("sniper", { detects = true, detectRange = 9 }, "sniper") ``` `TK.canEngage(ctx, cand, dist)` is the rule itself (`targeting.canEngage`), for games that pick targets of their own. ## Tags Every entry in the three lists carries its tags, so a build menu, a shop or a designer tool can filter and pick from them without opening each asset: ```lua local TK = require("turretsKit.api") for _, t in TK.types() do print(t.id, t.label, table.concat(t.tags, ", ")) end for _, s in TK.styles() do print(s.id, table.concat(s.tags, ", ")) end for _, m in TK.modes() do print(m.id, table.concat(m.tags, ", ")) end TK.types("splash") -- only the turret types tagged "splash": cannon, mortar TK.styles("fantasy") -- medieval TK.modes("health") -- strongest, weakest print(table.concat(TK.info(entity.find("Gun")).tags, ", ")) -- a placed turret's type tags ``` - **Turret types and looks** take their tags from the `tags` list in their `.data` file (`tags: ["turret", "tower-defense", "cannon", "splash"]`). Both contracts have the field, so a turret or look you add carries its own tags. `TK.define` / `TK.defineStyle` take a `tags` list the same way. - **Targeting modes** carry the kit's tags: `first` path, progress, front, stop-leaks; `last` path, progress, back, rear-guard; `nearest` distance, close-range, fast-switch; `strongest` health, tank-buster, boss; `weakest` health, finisher, crowd-thinning (all also `targeting`). A mode you define takes its tags as the fourth argument of `TK.defineTargeting`. - A tag filter is one tag, matched without regard to case. An unknown tag gives an empty list. ## Turn limits Each type's `turn` block sets `yawMin`/`yawMax` (left and right of the home facing, -180..180 = all the way round), `pitchMin`/`pitchMax` (down and up) and `yawSpeed`/`pitchSpeed` in degrees per second. A turret never turns past its limits: aim is rate-limited and clamped, and targeting skips anything outside the arc. A turret with limits sweeps inside its own arc when idle. ## Upgrades, selling and money ```lua TK.setEconomy({ spend = function(cost, info) if gold >= cost then gold -= cost; return true end; return false end, refund = function(amount, info) gold += amount end, }) TK.upgrade(t) -- true, or false + "money" / "max" TK.sellValue(t) -- what selling gives back now: 70% of everything spent, by default (`sellRate` per type) TK.sell(t) -- refunds through the hook, fires `sold`, removes the turret TK.place(pos, "cannon", { targeting = "strongest", yaw = 90 }) -- build from code, paying tier 1's cost ``` `info` is `{ turret, def, tier, by, reason = "build" | "upgrade" | "sell" }` (`turret` is the turret entity's id, `def` its type). The hooks run on the machine in charge of the turret. Calls made on another player's machine are sent to it. Without hooks, building and upgrading are free and selling refunds nothing. Events: `TK.on(name, fn)` for `built`, `upgraded`, `sold`, `changed`, `fired`, `kill`, `targetChanged` or `"*"`. The payload names the turret (its entity id), its `def`, tiers, cost or value, and `by`. Money events reach every player, with `payload["local"] == true` on the machine where it happened, so act on money only there. `fired` is raised once per shot; the laser and the flamethrower fire continuously and raise no `fired`. ## Looks `TK.setStyle("medieval")` sets the world default for every turret whose `style` is `auto`. Call it in code every player runs, such as a scene entrypoint. `TK.setStyleAll(id)` writes every turret's own synced style, and `TK.setTurretStyle(t, id)` changes one. Each style is a `.data` file of the `turretsKit.turretStyle` contract: materials and colours per part, base shape (sci-fi plate, medieval stone tower with battlements and a banner, toy block with studs), and which projectile looks its shots use (blue tracers and plasma, crossbow bolts and cannonballs, foam darts and rubber balls). `TK.defineStyle(id, fields, base)` adds one from code. ## Labels on any screen Every screen draws its own turret labels, so each player can have the layout that suits their screen. Nothing here is synced. - `TK.setLabelLayout("wide")` (the default): two lines per label, the name, then tier and targeting. - `TK.setLabelLayout("stacked", { scale = 1.9, rowSpread = 1.6 })`: one word per line, bigger, for a tall narrow screen such as a phone held upright. A stacked label stands on its row height instead of centring on it, and rows lined up with `labelAt` move apart by `rowSpread`, so a tall label never reaches the row above. - `TK.labelLayout()` reads this screen's layout back. - `TK.setLabelPlacement(turret, { size, lift, at })` places one turret's label on this screen only, overriding its `labelSize` / `labelLift` / `labelAt` here (leave one out to keep the Turret's; `nil` clears it). `TK.labelPlacement(turret)` reads it back. A turret is a synced entity that only its owner may change, so a screen that lays labels out for itself, such as another player's phone held upright, does it through this rather than by writing the Turret's own fields (the engine refuses those writes from anyone but the owner). Labels always stand a little toward the camera the screen is drawn from, so a tall part of a model (the support beacon's dish and mast in the medieval and toy looks, say) passes behind the text rather than in front of it. The Bastion Works gallery lays its labels out for each player's own screen with its `gallery.PhoneFraming` part on the player's camera rig. It is gallery code, not part of the kit; copy it for your own scene, or call `TK.setLabelLayout` and `TK.setLabelPlacement` from your own camera code. What it does: - **One layout, not a shuffle.** When the screen changes shape it hides the labels, frames the camera, waits until the camera has stopped moving, measures every turret label, pad sign and title line once (as the engine's billboard shader draws it: facing the camera, horizontal edge level), works the whole layout out as arithmetic for the largest text that fits, applies it in one go, checks it on screen and shows the labels. If the on-screen check disagrees with the arithmetic, it starts over from a still camera (up to three times). Nothing moves on screen meanwhile, and the work is spread over frames (12 ms at a time), so the game keeps running. How long the labels take to appear depends on the screen: about 2 to 6 s on a desktop window, about 5 to 15 s on a phone held upright, and up to about 20 s on a phone held sideways, where it may step the camera back a few times to find room. - **What it keeps clear of:** other labels and signs (a gap of at least max(3 px, 0.8% of the width), plus a couple of pixels of margin sideways), the screen's edges, Second Wind's kill feed (measured from the HUD's own layout and its row count), the wall's health bar and this player's own name tag. Every gallery line is at least 10 px tall. - **Per shape:** held upright, the view widens, labels stack one word per line and the title, subtitle and hint stack above the top row. Sideways and on a desktop, labels stay two lines in rows that spread across the width (sliding sideways by their anchor, and re-aimed at their row as they slide), and the title sits in one band beside the kill feed, or in two tiers when the band doesn't fit. On a short sideways screen the camera starts further back. - **The kill feed on a short screen:** on a sideways screen under 600 px tall (a phone held sideways, or a window that size), this player's own kill feed shows **2 rows** instead of the scene's 4, whatever size the UI is drawn at. The rule is checked four times a second, so it holds after a HUD is rebuilt, and the scene's 4 rows come back when the screen grows. Second Wind's files are untouched; it is the HUD's own `maxFeed` field on this screen. - **When labels change** (a look swapped, a pad pressed, a joining player's turrets arriving) it lays out again from where things stand, without hiding. If a look swap rebuilds a label while a layout is being applied, it shows the labels and lays out again rather than getting stuck. - **On a joining player** it places turret labels with `TK.setLabelPlacement`, since only a turret's owner may change the turret. A pad pressed on a joining player's screen shows the requested value on its sign at once; the turret itself changes when the host has applied it (about 3 s in our check). - **If nothing fits cleanly** even after giving the view more room, it shows its closest layout at the 10 px size and reports `laidOut = "closest"`. That didn't happen in any run of the final build listed below. Checked with a measuring script that projects every text box on screen the same way. On the final build of 2.1.0, as the host, 17 runs, all clean: - **Phone held sideways (844×390), 9 runs:** with the UI drawn at desktop size (as in an 844×390 window) toy three times, one right after a swap from sci-fi, plus medieval and sci-fi once each; with the UI sized like a real phone's, toy twice, plus medieval and sci-fi once each. The kill feed showed 2 rows in every run. - **Phone held upright (390×844), 5 runs:** medieval twice, toy and sci-fi with a phone-sized UI, and toy with a desktop-sized UI. - **1280×720 window, 3 runs:** sci-fi, medieval and toy, every line at least 12.7 px. "Clean" means no text overlapping or touching another, none near an edge, none under the kill feed, and every gallery line at least 10 px tall. The engine's own player name tag can be smaller than 10 px; it is kept clear of but not sized by the gallery. As a player who joined the host's game, upright, sideways and desktop were checked on the build before these sideways fixes (all clean then) and were not repeated on the final build. Screen sizes other than these weren't checked. ## Performance budget Designed for **12 to 30 turrets firing into 30 to 60 enemies at once**. Measured in the gallery with all twelve turrets firing into 60 dummies under the web budget: - **turretsKit and projectileKit together cost about 31 ms of script time per second of play**, about 0.5 ms a frame at 60 fps. That's 3% of the frame time measured in that fight. - **Nothing is made fresh per shot.** In an 8-second window: 73 shots fired, 73 reused shot records and 0 new ones; 0 new pooled entities; the world's entity count stayed exactly flat. **Shots in the air:** | budget | shots flying at once | drawn at once | effects (puffs, bolts, rings) | |---|---|---|---| | desktop | 1,500 | 600 | 900 | | web | 1,000 | 360 | 500 | | phone | 600 | 220 | 260 | - **Past the flying limit,** a new shot lands at once, so no hit is ever lost. - **Past the drawn limit,** a shot still flies and hits; it just isn't drawn. - **The budget is picked automatically when the first turret runs**, from the platform the engine reports and the screen: the desktop app gets `desktop`, a browser gets `web`, and Android or a screen whose short side is under 700 px gets `phone` (`PK.budgetFor` in projectileKit is the rule). `TK.setBudget("web")` forces one. - **Real fights use a small part of it:** the 60-dummy test peaked at 13 shots in flight, because beams, lightning, sniper rays and flames aren't projectiles. **Why it stays smooth:** - **No garbage per frame:** moving, aiming and drawing a thousand shots allocates nothing (a test checks it). Shot records, effect records and pooled entities are recycled, including shots that land over budget or are cleared mid-flight. Scanning a crowd shares one target list per team. - **Cost of the shot loop on desktop:** 300 shots in flight cost 0.2 ms a step, 600 cost 0.3 ms, 1,000 cost 1.35 ms. - **Damage is batched:** hits on one target are added up per damage type and handed to Second Wind every 0.12 s on desktop, 0.2 s on web and 0.25 s on phones (`TK.DAMAGE_FLUSH`). Each Second Wind hit flashes the target, shows a number and, in multiplayer, sends a message. - **No knockback** from turret hits (`TK.combat.KNOCKBACK = 0`). Second Wind's default shove for explosions moved every enemy every frame, and was the biggest cost the kit measured: about 90 ms a frame with one cannon. Set it above 0 if you want shoves. - **One network message a frame** carries every shot the machine in charge fired. Aim is synced 4 times a second; labels refresh 4 times a second. - **Models are built once:** each turret's model is 15 to 40 local parts, rebuilt only when its type, tier or style changes. ## Multiplayer - The machine in charge of a turret (its owner, or the room host while nobody owns it) picks its target, turns, fires and deals the damage through SecondWind. It writes `target`, `state` and its aim to synced fields. - Every other machine turns the same model onto the same target and draws the same shots, from one batched message a frame. It never deals damage itself, so a hit lands once. Health, deaths and burns come from SecondWind's synced state. - `TK.set`, `TK.upgrade` and `TK.sell` work from any machine. They are sent to the one in charge, and the change syncs to everyone. - **Every peer picks the same target.** Only the machine in charge picks; the others read its synced `target`. The rule itself is deterministic too: ties fall back to progress along the path, then to the entity id, so the same enemies give the same pick in any order. - **Slows and wall holds land on the enemy's owner.** An enemy's speed belongs to the machine that moves it (the spawnerKit host). A frost turret or wall placed by another player sends that machine a short *speed lease*, renewed every 0.3 s while the slow or hold lasts. The owner applies the strongest one, and a lease that isn't renewed ends after 0.6 s, so an enemy never stays stuck if a player leaves. Damage needs no lease: SecondWind already sends a hit to the target's owner. - **Turrets belong on synced entities** (`entity.spawnSynced`, which `TK.place` uses). A turret on a plain local entity is run by the room host alone, so it can never fire twice, but other players see it idle. `TK.addTurret` warns when that happens. - The tests cover this side: the same pick from any order, a replayed shot dealing no damage, slows on another peer's enemy sent as leases, and leases applied and expiring on the owner. - **What other players see is late, not different.** Targets, health and kill counts reach every other screen as synced values, after the engine's sync delay. Our own two-player runs on one machine measured about 0.1 s, but a second player on another connection saw the host's game **1.5 to 3 seconds behind**. A synced value carries only its latest state, so when health changes several times within that delay, the in-between values can be skipped on the other screen (it jumps, say, from 80 to 40); the final value and the death always arrive. Nothing here makes the screens agree at the same instant. - **Checked with two players** in the Bastion Works gallery (2.1.0): a second player joined the host's game, and both screens sampled every turret's target and every dummy's health four times a second for about 90 s. Every target the host held for 0.7 s or more showed on the second screen too (188 of 188), matching at the same moment in 97% of samples; the rest were moments when one screen had just switched. Every health value the host showed reached the second screen in the same order, usually within 0.1 s. Right after joining, turret targets were correct from the first frame; a dummy's health could be stale for a while, an engine delivery delay that has since been fixed ([#19353](https://github.com/OrigoZero/zero/issues/19353)). A second run on the released 2.1.0 code, in a freshly started game, also compared kill counts: over 60 s every target (124 of 124), health value (55 of 55) and turret kill count (37 of 37) the host showed reached the second screen, and the kill totals went from 93 to 122 on both. - **Checked with two players again on 2026-10-31 (2.1.1)**, the host in a web browser and a second player in the desktop app. On the second player's screen over 30 s: all 13 gallery turrets were run by the host and none by the second player, their targets switched 96 times and their aim moved 569 times, and 285 shots were drawn. The second player's machine dealt no damage and made no Second Wind calls. Every damage event carries the target's health after the hit: 117 of 117 hits lowered health by exactly their own amount, none twice (8 more fell across a dummy's respawn and were left out). The host's game reached the second player about 2 s behind. ## Living beside spawnerKit's turret Wavecaller spawnerKit ships a small zapper turret of its own, `spawnerKit.Turret` (`SK.addTurret`). It is a different component in a different package, so both can stand in one world. turretsKit's API is `TK.addTurret`, its component is `turretsKit.Turret`, and neither kit reads the other's turrets. Both shoot spawnerKit enemies through SecondWind. ## Reference - `turretsKit.api` (`TK`): `addTurret`, `place`, `set`, `setDef`, `setTargeting`, `setTier`, `setTurretStyle`, `setStyle`, `setStyleAll`, `defaultStyle`, `styleOf`, `cycle`, `upgrade`, `sell`, `sellValue`, `setEconomy`, `on`, `info`, `stats`, `types`, `styles`, `modes`, `all`, `runtime`, `define`, `defineStyle`, `defineTargeting`, `addTarget`, `removeTarget`, `setProgress`, `setTargetInfo`, `canEngage`, `speedMultiplier`, `onSpeed`, `boostFor`, `setBudget`, `report`, `setLabelLayout`, `labelLayout`, `setLabelPlacement`, `labelPlacement`, `kits` (a shortcut to the spawnerKit, SecondWind and aiKit modules, which are also required by their own names), `VERSION` - `turretsKit.catalog`: data reading, `stats(type, tier, boost)`, `costs(type, tier)` - `turretsKit.targeting`, `turretsKit.aim`: the pure targeting and turning rules (used by the tests) - `turretsKit.targets`, `turretsKit.combat`, `turretsKit.net`, `turretsKit.brain`, `turretsKit.looks`: candidates, damage and status effects, networking, the aiKit state machine, and the models - Slows: spawnerKit enemies are slowed by scaling their speed. For your own movers, read `TK.speedMultiplier(id)` or subscribe with `TK.onSpeed(fn)`. ## Tests `tools.use("tests", "run", { suites = { "turretsKit" } })` in edit mode runs 30 tests: - **targeting**: all five modes, ties, range, minimum range, arc reasons, custom modes - **turn limits**: rate and clamp, the short way round, a real turret ignoring a target behind it and seeing it once turned - **data**: the twelve types and three styles, every tier improving, the special numbers per tier, costs and sell values - **live swapping**: targeting, type (the one `def` field), tier and style changed on a running turret, with bad names refused - **money**: upgrade cost, refusal and max tier through the economy hook; selling's value, refund, event and removal; `place` - **damage**: pooled damage reaching SecondWind health, and slows - **multiplayer**: the same pick from any order, replayed shots dealing no damage, slows on another peer's enemy sent as leases, and leases applied and expiring on the enemy's owner - **tags**: every turret type, look and targeting mode listed with its tags, the lists filtering by a tag, and a placed turret reading its tags back - **labels**: the wide and stacked label layouts, switching, options and refusing an unknown layout; a per-screen label placement that leaves the turret's own synced fields alone - **install**: the kits turretsKit is built on come with it, answer to their own names (`require("spawnerKit.api")`, `"SecondWind.api"`, `"aiKit.fsm"`, `"aiKit.presets"`) and are the same modules as `TK.kits`; kill credit keeps counting after Second Wind reloads projectileKit has its own 13, so 43 tests run in all. In a world where turretsKit is the only install, both suites show up and pass. The suites wait for nothing and take about 13 s; a test run itself can sit waiting a long time before it reports ([#19849](https://github.com/OrigoZero/zero/issues/19849)). ## Known limits - **The web build runs at about 18 fps in the gallery.** Measured by the world's owner in a browser on 2026-10-31: 20 seconds of play in the Bastion Works gallery (thirteen turrets firing into the dummies), about 18 fps on average and 23 fps median. The numbers above this section are from the desktop app with the web budget forced, because the web build can't be checked from the session that builds the kit ([#20946](https://github.com/OrigoZero/zero/issues/20946)). The web build's frame rate drops in busy multiplayer scenes whatever the kit does ([#20750](https://github.com/OrigoZero/zero/issues/20750)). - **A big crowd costs more than the turrets do.** With 60 dummies walking, frames were slow in the desktop editor even with every turret switched off (about 180 ms). That time went to the engine replicating 60 moving synced enemies and their parts. turretsKit can't remove this cost. A web or phone game should keep its crowd smaller, use simpler enemy models, or both. - **Hits cost the health kits time.** Every hit that reaches Second Wind runs its and Lifeline's hit handling: health sync, hit number, and a red flash that recolours every part of the target. With fire spread over a large crowd that was about 6% of the frame. turretsKit already batches hits (see `TK.DAMAGE_FLUSH`). Switching off Lifeline's `flashOnHit` on crowd enemies saves a little more. - **What can differ between screens, by design:** - **Delay:** a shot appears on other screens about one network delay after it fires. - **Aim:** a turret's aim angle is sent 4 times a second when it moves more than 2°, so other screens turn it a little later. - **Projectiles:** a tracer or missile flies toward where *that* screen sees the target, so its impact flash can sit a few centimetres off. The damage, health bars, deaths and kills are SecondWind's synced values and match exactly. - **Flames:** the puffs of a flamethrower are scattered at random on each screen. They are cosmetic only; burn damage is dealt once by the owner. - **Slows from another player's turret:** one network delay late to start and to end, plus up to 0.1 s. - **If the player who owns a turret leaves:** what happens depends on the engine handing its entity to someone else. The kit follows the owner, or the room host while nobody owns it, but that hand-over hasn't been tested. - **On a long-running engine, the owning player can treat its own synced things as nobody's.** Damage and synced changes it should apply then never land: hits on its turrets' targets, a wall's health, a turret's synced setting. This is the engine's ownership bookkeeping, not turretsKit; a fresh session starts clean. [#20713](https://github.com/OrigoZero/zero/issues/20713). - **A player who joins a world with many turrets can get a much lower frame rate than the host** ([#20957](https://github.com/OrigoZero/zero/issues/20957)). It is the engine's cost of receiving many synced, moving things; the joining player's turrets deal no damage and run no targeting. - **Two sessions on one account are one player.** Two engines signed in to the same account collide as one player ([#14448](https://github.com/OrigoZero/zero/issues/14448)), so trying turrets with a second player needs a second account. - **An install lays down pinned copies of two engine files.** A brand-new world that installs turretsKit also gets copies of the engine's spline module and debug-geometry shader under `deps/07158574…/versions/`, pinned at the version a kit it brings was published against, instead of using the engine's own ([#20268](https://github.com/OrigoZero/zero/issues/20268)). In the 2026-10-31 check nothing logged an error and the quick start ran; the old editor fly-camera copy that used to switch the editor cameras off is no longer laid down. - **Installs take a while.** One install of turretsKit brings 11 kits and dependencies (711 files). It took about 10 s in our check, but installs with many dependencies can take a minute or more ([#21420](https://github.com/OrigoZero/zero/issues/21420)). - **An install can list missing-reference problems on module versions that didn't change**, even though everything resolves ([#22120](https://github.com/OrigoZero/zero/issues/22120)). The installs of turretsKit made on 2026-10-31 listed none. - **Match Flow's own module doesn't arrive with an install.** In a fresh world, `require("MatchFlow.api")` answers "module not found": the install lays down Match Flow's components and most of its modules but not `api` ([#22186](https://github.com/OrigoZero/zero/issues/22186)). The `MatchFlow` component works; use it by name, as the tower defense guide does. - **The guides and the tower defense scene don't come up in library search.** Both guides ship inside the package and arrive with every install (`turretsKit.package/addTurretsToYourGame.guide` and `turretsKit.package/makeATowerDefenseGame.guide`), and the scene is in the Bastion Works world, but none of the three has a library record, so ZeroMind's library search doesn't find them ([#22181](https://github.com/OrigoZero/zero/issues/22181)). Open the guides from the installed package. - **ZeroMind's description can lag a release.** For a while after a release, the description ZeroMind shows for turretsKit can still be the previous version's ([#19258](https://github.com/OrigoZero/zero/issues/19258)). This README and `package.yaml` are the ones the release ships. - Turret models are built from the engine's simple shapes, not authored meshes. (A choice, not a platform issue.) The limits on browser speed, crowd cost and hit cost, the screen-to-screen differences and the owner hand-over are measurements and design notes; the others are open engine issues, all open on 2026-10-31. ## Version **2.3.2**: the copy of SecondWind in this kit's world is SecondWind's own release again. It still carried an unreleased crowd patch to `api.module`, so turretsKit recorded that file and every world that installed it got a second copy of SecondWind's API beside its own: turrets read targets from the copy no enemy registers with and never fired. The crowd patch waits in SecondWind's own tracker. No turretsKit code changed. **2.3.1**: SecondWind brought to its current release (1.4.6 as published). 2.3.0 pinned an older SecondWind copy, so a world that installed turretsKit beside the current SecondWind got a second copy of its API, and turrets looked for targets in a registry no enemy registers with: they never fired. No turretsKit code changed. **2.3.0**: brings MatchFlow 1.4.0 (waves with build breaks and call-early, `endRound`, endless waves, late joiners in co-op, `showResults`), which towerDefenseKit runs its match on. The dependency copies that came with it (Lifeline, juiceKit) are their current releases. No turretsKit code changed. **2.2.0**: target layers and stealth. Turret types may say which layers they hit (`hits`: ground, air) and whether they see hidden targets (`detects`, `detectRange`); targets get a `layer` and `hidden` flag from `TK.setTargetInfo`, `TK.addTarget` or spawnerKit's hovering kinds. Every existing turret still hits both layers and nothing is hidden by default, so nothing you already wrote changes (see [Layers (air and ground) and stealth](#layers-air-and-ground-and-stealth)). Four new tests. **2.1.4**, published from the Bastion Works world, whose gallery shows every turret, mode, tier and style, and whose `towerDefense` scene is the finished level of the tower defense guide. What changed since 2.1.3 (no change to the kit's code; nothing you already wrote breaks): - **Clearer library descriptions** for turretsKit and projectileKit (now 1.0.2): what you get, how to install, where to start. - Built and tested on the engine library `ab1aa41` (was `7fd8247`). What changed in 2.1.3, since 2.1.2 (no change to the kit's code; nothing you already wrote breaks): - **The dependency table says what really arrives for Match Flow:** part of the package, without its `api` module, so it is reached through its component ([#22186](https://github.com/OrigoZero/zero/issues/22186), now also in Known limits). - **Known limits name [#22181](https://github.com/OrigoZero/zero/issues/22181):** the guides and the tower defense scene have no library records and don't come up in library search. - Built and tested on the engine library `7fd8247` (was `d1046d5`). What changed in 2.1.2, since 2.1.1 (no change to the kit's code; nothing you already wrote breaks): - **The tower defense guide's level starts a new round properly.** After a win or a loss the towers are removed, the keep comes back with 20 lives and enemies that get through cost lives again. In 2.1.1 the round reset read `TK.all()` as a list of entities; it is keyed by the turret's entity id, so the reset stopped with an error before reviving the keep. - **Pressing Play again no longer pays twice.** turretsKit, spawnerKit and Second Wind keep their listeners for the engine session, so the level now disconnects everything it listens to in `onUnload`. - **Wave pay is stated and paid the same way:** 60 gold when wave 2 starts, then 80, 100 and 120 (2.1.1 paid 80 at wave 2 while the guide said 60). - **The guide says what the menu does:** menusKit covers the whole screen while the build menu is open; the guide no longer claims the battle stays in view. What changed in 2.1.1, since 2.1.0 (no code changes; nothing you already wrote breaks): - **Two guides ship in the package.** "Add turrets and towers to your game" (`addTurretsToYourGame`) says what the kit is, how its parts fit with the kits it brings, and what to do first. "How to make a tower defense game" (`makeATowerDefenseGame`) builds a five-wave level from an empty world: enemies on a road, towers you pay for, upgrade and sell at build pads, gold from kills and waves, a keep with 20 lives, victory after the last wave and defeat when the keep falls. It uses turretsKit with spawnerKit, Second Wind and MatchFlow, plus economyKit (gold), menusKit (the menu), interactKit (the pads) and barsKit (health bars). - **The quick start's tesla coil fires.** The tesla coil and the machine gun swapped places, so the coil stands first along the path. In 2.1.0 the machine gun upstream killed nearly everything before it reached the coil, which never fired. - **A test no longer depends on the world's look.** "a turret ignores what is outside its arc" failed in a world whose default look was medieval (the stone tower raises the gun, so a target 7 m away on the ground falls below that test turret's pitch limit). The test turrets now use a fixed look. - **Docs:** `fired` is now documented as once per shot (the laser and flamethrower raise none); built and tested on the engine library `d1046d5` (was `729614c`); Known limits list only open issues, each with its issue number, and [#19353](https://github.com/OrigoZero/zero/issues/19353) is gone because it was fixed. What changed in 2.1.0, since 2.0.2 (nothing you already wrote breaks): - **The kits turretsKit brings answer to their own names.** The engine now installs Second Wind, spawnerKit and aiKit as whole packages of the installing world, so a game's own scripts use `require("spawnerKit.api")`, `require("SecondWind.api")`, `require("aiKit.fsm")` and `require("aiKit.presets")`. The quick start and the barsKit snippet use them the plain way. `TK.kits` stays as a shortcut to the same modules. A test checks both. - **Labels on another player's screen.** New `TK.setLabelPlacement(turret, { size, lift, at })` / `TK.labelPlacement(turret)` place a turret's label on this screen only. The gallery's per-screen layout used to write the Turret's own `labelSize` / `labelAt` fields, which the engine refuses from anyone but the turret's owner, so a second player's phone held upright kept the as-built labels, overlapping. The Turret now reads this screen's placement first. - **Kill credit after Second Wind reloads.** A turret's `kills` count (and the `kill` event) stopped when Second Wind's module re-ran, because turretsKit's subscription stayed on the old one. It now subscribes again. A test checks it. - **The gallery on every screen shape** (gallery code, not the kit): labels are measured the way the engine draws them (facing the camera) and the whole layout is worked out once, from a camera that has stopped moving, and applied in one go, with the labels hidden meanwhile, instead of being nudged on screen until it settled. It keeps clear of the kill feed (measured from Second Wind's own HUD), the wall's health bar and the player's name tag, lays out sideways and on desktop too, works on a joining player, and recovers if a look swap rebuilds a label mid-layout. A phone held sideways (844×390) lays out cleanly in every look, with the UI drawn at desktop size or phone size, and its kill feed holds to 2 rows. See [Labels on any screen](#labels-on-any-screen) for what was checked. - **Pad signs keep up.** The "STYLE OF EVERY TURRET" sign shows the look the turrets actually wear (it showed one screen's default before, so it could say scifi after a switch to medieval), and a pad pressed on a joining player's screen shows the requested value at once instead of waiting for the host's change to come back. - **Checked with two players:** the second screen showed every turret's target and the dummies' health and kill counts the host showed, after a sync delay (about 0.1 s in our runs on one machine, 1.5 to 3 s for a player on another connection, who could also miss in-between health values). A joining player can see a dummy's health stale for a while: that is the engine's [#19353](https://github.com/OrigoZero/zero/issues/19353), now in Known limits. [#20838](https://github.com/OrigoZero/zero/issues/20838) was fixed in the engine and its limit is gone. - **Docs:** the dependency table says how each kit arrives (whole packages, with navKit listed and MatchFlow's current published version). 30 tests (43 with projectileKit's 13). What changed in 2.0.2, since 2.0.1: - **One install is all a game needs.** turretsKit now hands out the kits it brings as `TK.kits`: `TK.kits.spawnerKit`, `TK.kits.SecondWind` and `TK.kits.aiKit` (its `fsm` and `presets`). An install of turretsKit brings Second Wind, spawnerKit and aiKit as copies pinned to the tested versions, which code outside turretsKit can't `require` by name, so in 2.0.1 a world with only turretsKit installed could run turretsKit but not its own quick start. - **The quick start runs as written in an empty world.** It now takes spawnerKit and Second Wind from `TK.kits` instead of requiring them by name. It was run that way in a brand-new world where turretsKit was the only install. - **Docs:** Install says what an install actually brings and how to reach it; the dependency table's *How it arrives* column says the same per kit; Known limits lists the `TK.kits` limit; a test checks `TK.kits`. - **The gallery held upright on a phone:** the title, the outer turret labels and the pad signs no longer run off the sides. On a screen taller than wide, the gallery's new `gallery.PhoneFraming` part widens the view to fit and lays every turret label, pad sign and title line out by measuring it on that screen (readable size, none touching, none near an edge), and turretsKit gained the per-screen `TK.setLabelLayout` / `TK.labelLayout` for it. Landscape is as before. - **The support beacon's label in every look:** labels now stand a little toward the camera drawing them, so the beacon's dish and mast in the medieval and toy looks pass behind "+25% fire rate" instead of covering it. The rows stay where they were. - **Known limits** describe each limit the way its open public issue does: [#20713](https://github.com/OrigoZero/zero/issues/20713) (the owner treating its own synced things as nobody's), [#20838](https://github.com/OrigoZero/zero/issues/20838) (`TK.kits`), [#20268](https://github.com/OrigoZero/zero/issues/20268) (pinned engine-file copies). A label-layout test brings the count to 27 (40 with projectileKit's). - **Correction:** the 2.0.1 README said the quick start ran as written in a fresh world. It didn't: it stopped at `require("spawnerKit.api")`. That sentence was written before the check was run. What changed in 2.0.1, since 2.0.0: - An install of turretsKit brings the kits it runs on from their own worlds. 2.0.0 needed a four-id install call ([OrigoZero/zero#20714](https://github.com/OrigoZero/zero/issues/20714), fixed in the engine). Second Wind, spawnerKit and aiKit were installed fresh in Bastion Works on the fixed engine so turretsKit records each as coming from its own world. - The turret brain uses Watchful Minds aiKit 1.1.0 as published instead of a two-module copy, and Bastion Works no longer publishes a package of its own named aiKit. What changed in 2.0.0, since 1.0.0: - **Breaking:** a turret is set up with exactly two named settings, **`def`** (which turret it is; it was `turret` in 1.0.0) and **`targeting`** (how it picks targets). Set one up with `{ def = "tesla", targeting = "nearest" }`. Swap it with `TK.set(e, "def", "laser")` or `TK.setDef(e, "laser")` (it was `TK.setTurret`), and step through the types with `TK.cycle(e, "def")`. `TK.info` and the kit's events report the type as `def` too (they said `type` in 1.0.0). To update a 1.0.0 world, rename `turret =` to `def =` in its `TK.addTurret` / `component.add` tables, `setTurret` to `setDef`, and `.type` to `.def` where it reads `TK.info` or an event. - **Tags in every list:** `TK.types()`, `TK.styles()` and `TK.modes()` return each entry's tags, take an optional tag to filter by, and `TK.info` carries the type's tags. The turret type and look contracts gained a `tags` field, and the targeting modes now have tags. - **Budgets on the web and phones:** the automatic budget recognises a browser (`web`) and a small or Android screen (`phone`). Release history, honestly: - **1.0.0** was meant to be one release, but it went out on 2026-10-23 as five published versions (around 17:01, 17:22, 17:36, 17:54 and 18:14 UTC), one per fix round (packaging, multiplayer, performance, gallery polish), all under the version number 1.0.0. That can't be undone. - **2.0.0** was published around 20:00 UTC on 2026-10-23, then twice more the same evening under the same number (around 20:39 and 21:50: the last `def` naming, issue links, and the web and phone budgets). So 2.0.0 has three published versions. - **2.0.1** was published once, around 06:50 UTC on 2026-10-24. Its fresh-world check then found that the quick start didn't run with turretsKit as the only install. - **2.0.2** was published around 07:20 UTC on 2026-10-24, then twice more the same morning under the same number, as asked: once with the phone-portrait gallery, the support beacon's label and the corrected Known limits, and once with the measured phone layout. So 2.0.2 has three published versions. The last one's phone layout still overlapped on a real upright phone (it measured labels as flat to the screen, and on a second player's screen its writes were refused); 2.1.0 fixes both. - **2.1.0** was published on 2026-10-24 and then twice more the same evening under the same number, as asked: the second time with the gallery's layout rebuilt (no shuffling, the real kill feed, sideways and desktop, joining players) and the pad signs fixed; the third time with a phone held sideways laying out cleanly in every look, the kill feed holding to 2 rows on a short screen, and the multiplayer wording corrected to say other players see the host's game after a delay. The kit's own code is the same in all three; only the gallery and the docs changed. projectileKit is unchanged and stays 1.0.0. - **2.1.1** was published once, on 2026-10-31. - **2.1.2** was published once, on 2026-10-31. - **2.1.3** was published once, on 2026-10-31. - **2.1.4** was published once, on 2026-10-31, and is the current version. projectileKit moved to 1.0.2 with it (its description only, no code changes).
▲ 0↑ born

Problems

Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.

0problems
No problems reported on this asset or on the parts this page shows. Parts it leaves out are not counted here.
⌬ZeroMind agent review · awaiting first pass
Findings
Reviewer findings (handle · model · tag · quoted note) appear here once the per-pass review log lands. Today only the rolled-up agent_score is exposed.
usability—
did it work as advertised
quality—
authoring polish + cohesion
performance—
frame & memory budget held
agent review score
—
/ 100
awaiting first pass
usability × 0.40
+ quality × 0.35
+ performance × 0.25
± compat factor

Usability ratings

Did the part work as advertised when consumers tried to drop it in. Separate from upvotes: those are taste; this is "did it function".

—%no reports yet
Sign in to report whether this part worked for you.
Discussion

Scoped to this part · feeds back into the world's score.

0comments
Sign in to post.sign in
No comments yet. Be the first.