Skip to content
Work in progress. These docs describe Spawnite at launch, and some parts are still being built.

Weapon

Weapon arms every player in the world with one weapon, under a name that is unique to it. It mounts once in the scene, not on an entity: the room’s world and each page’s world hold the same weapons, because both mount the same scene.

Its props are in WeaponProps, which are the weapon’s WeaponSettings plus name and the pointer button it fires on, primary by default.

List weapons() from @spawnite/engine/weapons in the game’s plugins, as Import entries says.

On a page, a click on the canvas fires the weapon from the middle of the player’s character toward what is under the pointer. A press that drags more than a few pixels turns the camera and fires nothing, and so does a click on the page’s own controls over the canvas. A downed character fires nothing, nor does a character with the engine’s DisarmedTrait trait, nor a character who does not hold the weapon.

While the camera holds the cursor captured, or holds its lock on a touch screen, the shot goes through the middle of the screen, where the crosshair is. There a press fires at once, and a held button fires at shotsPerSecond while automatic is on, its default; with automatic: false the weapon fires once per press, on its release. A click, a held button, the fire button and auto-fire share one rate, so no way of firing outpaces shotsPerSecond.

An instant shot draws its tracer, and a hit marker where the page shows a hit, at once: a larger gold one where it strikes one of the target’s weak spots. The room’s verdict arrives later as the target’s health. When a rule refuses the shot, the room tells the page, and the page takes its hit marker back. The room’s result for the shot names the zone it judged the shot struck, and a gold marker turns plain where the room judged a body hit. With no room, the page deals the damage or launches the projectile itself, but an instant shot fires only its middle pellet and pierces nothing.

kind picks one of the two WeaponKind values:

  • WeaponKind.Instant, the default, hits at once. The room rewinds each target to where the shooter’s screen showed it as the shooter fired, and judges the hit there. Each pellet hits the nearest target on its ray, plus as many behind it as pierce allows, unless the ground, a wall, a rock or a prop stands nearer. pellets fans that many rays level with the ground, spread radians apart.
  • WeaponKind.Projectile launches a body that the room flies at speed metres a second, drawn as model. It needs no rewind: it hits the first target in its path as the room steps it.

Before it judges a shot, the room runs the shot’s rules. A rule can refuse the shot, and the rewind rule can move the moment the shot is judged at. A shot that passes every rule is judged. A shot passes through the shooter’s ally while friendly fire is off: with no teams(), every other player’s character, and with teams(), the shooter’s teammates, as Teams says. A weapon’s friendlyFire overrides the world’s setting.

A game with no code gets every rule below, so one player with a modified page cannot ruin a room. A game that wants something else loosens a rule, turns it off, adds its own, or trusts the players’ pages.

Each rule has a name. The room runs them in the following order and stops at the first that refuses:

Rule What it does Why it exists What it costs an honest player
armed Refuses a shot from a downed character, or one with the engine’s DisarmedTrait trait. A page that ignores the downed state fires anyway. Nothing: the shooter’s own page fires nothing then either.
held Refuses a shot from a weapon the character’s HeldWeaponsTrait leaves out. A character without the trait holds every weapon. A page that fires a gun its player never bought, or one the player swapped away. Nothing: the player’s own page fires only what the character holds.
rate Holds the shooter to the weapon’s shotsPerSecond, as the shooter’s stats give it, with a burst of the shots that rate earns in 0.65 s, plus one, and never fewer than two. A page that fires faster than the weapon allows. Nothing up to a 0.65 s network stall: the shots a stall holds back land together, and all count. Past that, the burst’s last shots are refused.
origin Refuses a shot that leaves from more than 2.5 m from the middle of the character’s body in the room. A page that fires from across the map, or from beside its target. Nothing on a network the rest of the room plays on: the player’s page runs the character at most about 2.5 m ahead of the room, at a 5 m/s run with 100 ms of travel.
cover Refuses a shot whose origin stands past cover from the middle of the character’s body, as the room’s world stands now. A page that fires from the far side of a wall. Rarely, a shot from a muzzle that pokes past a wall’s edge the character stands against.
rewind Judges the shot at the moment the shooter’s screen showed, held within 200 ms of the shooter’s measured latency and at most a second back. A moment outside is judged at the nearest edge. Refuses nothing. A page that names whichever past moment put a target on its ray, which is called backtracking. A target is hit where the shooter saw it, up to a second after it moved or reached cover on its own screen. A shot the shooter’s network delayed more than 200 ms past the shooter’s usual is judged at the edge.

A weapon the world does not hold is always refused, under the name weapon, since there is nothing to judge.

The room measures each player’s latency from the player’s shots. Each shot names the room’s step the player’s screen showed as the player fired, and the room notes how long before its own step that was as the shot lands: the player’s round trip plus the delay the player’s page draws the world at. The player’s LatencyTrait trait holds the middle of the last eight samples, their jitter, which is how far they spread round it on average, and the eight themselves. The rewind rule reads it.

So the rewind follows each player’s own connection. A player at 100 ms with 80 ms of jitter is judged where the player saw their target, and so is a player at 300 ms. Valve’s Source engine rewinds the same way. It rewinds by the latency it measures, plus the delay the client draws at, at most sv_maxunlag, a second by default. When a command names a moment more than 200 ms from that, Source judges it at the measured latency. This room judges it at the nearest edge instead, which is closer to what an honest player saw.

The player’s first shot has no latency to hold it to, so the room judges it at the moment it names, at most a second back. A page cannot see the player’s latency before the first shot, and a check that needs it before then reads no samples.

The rewind stops a page from picking, shot by shot, the past moment that puts a target on its ray: each shot is held within 200 ms of the page’s usual delay. It cannot stop a page that claims a long delay on every shot, because the room measures the delay from the steps the page names. Such a page plays as a player on a slow connection does, and it reaches no further back than the second. Source has the same limit for a client that delays its own packets. A game where that matters tightens maximumSeconds, or adds a rule that reads LatencyTrait, as the example under Write a game’s own rule does.

A game sets its rules with registerShotSettings. Pass a plugin’s setup writer, or register from a logic component with useSetupEffect, as the following sample does. rules overrides the engine’s rules by name:

  • A rule under an engine rule’s name replaces it, in its place. originRule, rateRule and rewindRule take options that loosen or tighten the engine’s rule.
  • false turns the rule of that name off.
  • A rule under a new name is the game’s own, run after the engine’s.

The scene registers the settings, so the room’s world and every page’s world hold the same. The following scene lets a shot leave from 4 m, rides out a two-second stall, and turns the cover rule off:

import {
originRule,
rateRule,
registerShotSettings,
useSetupEffect,
} from "@spawnite/engine";
/** Mounted in the scene, so the room's world and every page's register it. */
export function ShotRules() {
useSetupEffect(
(writer) =>
registerShotSettings(writer, {
rules: {
origin: originRule({ metres: 4 }),
rate: rateRule({ stallSeconds: 2 }),
cover: false,
},
}),
[],
);
return null;
}

A weapon’s own rules lie over the game’s the same way, for that weapon alone. A lance whose beam starts at its tip, 3 m ahead of the character, loosens the origin rule for itself: <Weapon name="lance" rules={{ origin: originRule({ metres: 3.5 }) }} ... />. A weapon that names a rule the game turned off turns it back on in its place.

rewindRule({ maximumSeconds: 0 }) judges every shot at the room’s present, which favors the target: a shooter on a slow connection has to lead their target. Turning the rewind rule off with rewind: false judges each shot at the moment it names, anywhere in the last second.

A rule is a function of one ShotCheck. It returns the reason it refuses the shot, in words a person reads in the room’s log, or undefined to let it through. The engine’s own rules are written against the same ShotCheck, so a game’s rule can read everything they read:

  • claim: the shot as the shooter’s page sent it, with its weapon, the step it names, its origin, its direction, and the hits it claims where the page claims any.
  • shooter: the shooter’s character and its traits, among them LatencyTrait and FiredShotsTrait, the shooter’s last 16 shots with the moment each named, the moment it was judged at, when it landed and what refused it.
  • weapon: the weapon’s settings, as the world registered them.
  • world: the room’s world as the shot landed. readViewPosition(world, entity, { player, step }) reads where any entity stood at a step of the last second, as the shooter’s screen showed it. readViewTrait(world, entity, trait, { player, step }) reads a trait of it as the shooter’s screen held it then, such as a game’s own shield. A page takes each send’s traits as it lands and draws the world toward it, so between two sends the shooter’s screen holds the newer send’s traits, and readViewTrait reads that send, as the room reads a target’s hit zones. A page whose frame takes several sends at once keeps each of them, as the room does, so the shooter’s page’s guess reads the place the room’s judgement reads. It reads a trait defined with history: true, which the room keeps in each send.
  • authority: the room’s authority, which writes what a rule keeps, such as a game’s own record on the shooter’s character.
  • landed and now: the room’s step and its clock, in milliseconds, as the shot landed.
  • step: the step the shot is judged at, which a rule may move, as the rewind rule does.

The following rule refuses a shot from inside a safe zone, and a shot from a player further than 400 ms behind the room:

import { readTrait } from "@spawnite/engine/core";
import { LatencyTrait, TransformTrait, type ShotRule } from "@spawnite/engine";
/** Metres round the origin where nobody fires. */
const safeZoneMetres = 10;
export const noShotsFromSafety: ShotRule = ({ shooter }) => {
const feet = readTrait(shooter, TransformTrait)?.position;
if (feet && feet.length() < safeZoneMetres)
return "Fired from inside the safe zone.";
if ((shooter.get(LatencyTrait)?.seconds ?? 0) > 0.4)
return "Fired from more than 400 ms behind the room.";
return undefined;
};

The scene adds it with registerShotSettings(writer, { rules: { safeZone: noShotsFromSafety } }), using the writer from useSetupEffect. A plugin’s setup can register it with its setup writer too. Its refusals carry the name safeZone.

A refusal is never silent. The room does the following for each one:

  • Counts it by the rule’s name in its next heartbeat, as refusedShots, such as { "origin": 2 }. A count that climbs in honest play says a rule is too tight for the game.
  • Logs a shotRefused line with the shooter’s character, the weapon, the rule and its reason, for up to four of each player’s refusals between two heartbeats.
  • Records it on the shooter’s character’s FiredShotsTrait, which the next shot’s rules read.
  • Tells the shooter’s page, where the page numbered the shot, as the engine’s page does. useRoom’s refusedShot holds the last refusal: the shot’s number, which sendShot returned, the rule and the reason. The engine’s Weapon takes its hit marker back. A game that fires from its own trigger compares the number its sendShot returned.

judge: ShotJudge.Page in registerShotSettings makes each player’s page decide what the player’s shots hit, as a Roblox game’s client does by default. The page names the targets each pellet hit on its own screen, and the room deals the weapon’s damage to each, as far as pierce allows. The room still runs the rules, so a game that trusts the page still holds the shooter to the allowed rate and to the character’s body. It also still deals only its own damage: a page names a target, never an amount.

Trust the page in a game where nobody gains by cheating: a party game among friends, or a game whose players play together against the game rather than against each other. The page’s word then counts even where the room’s copy of the world disagrees, such as where a target stood a little further on. The room judges the zone of each target a page names itself, where the target stood on the shooter’s screen: a zone multiplies the damage, and a page names a target, never an amount.

A weapon sets judge for itself, over the game’s. The engine’s Weapon claims its hits when the page judges it, and so does a room’s bot. A game that fires from its own trigger claims them with claimShotHits and sends them in sendShot’s hits. A room refuses nothing for a claim: it skips a target it does not hold, one the shot spares, one the shooter’s screen never showed, and one with no health left.

A melee strike on a key with a cooldown is an ability of AbilityKind.Area: it strikes every hostile target within its radius of the caster, and the engine casts it from a key, spends its cost and counts down its cooldown. Write your own only when the strike needs more than that, such as an arc in front of the caster.

A game that fires its own weapon, such as a turret, a charge shot or a melee swing with an arc, sends a command rather than a shot. It gets the same rewind as an engine weapon, with no step in its payload. Every command a page sends names the room’s step the player’s screen drew, and the room holds that step within the player’s latency’s bounds as it admits the command, as the rewind rule holds a shot’s. Its room system judges the shot with an ordinary query that takes the command as its rewind:

  • castRay, castRayAll, castShape and overlapShape take rewind: command, and meet every other entity the stream draws, with a body that moves, where the shooter’s screen showed it as the shooter fired. Fixed bodies and the ground stand where they are, and so do the shooter’s own predicted entities: the shooter’s character is met where it stands now, so a query from that body passes ignore: [character]. An entity the shooter’s screen never showed, or one that teleported or respawned since, is not met. In a game played alone the query meets the present, so one system serves both.
  • readViewPosition(step, entity, command), readViewRotation(step, entity, command) and readViewTrait(step, entity, trait, command) read one entity as the shooter’s screen showed it, for a test a body’s colliders do not make, such as hit zones. readViewTrait reads a trait every send keeps: HitZonesTrait, HealthTrait, CharacterTrait for the character’s movement, a state machine’s trait where the machine’s reach is Reach.Everyone, and a game’s own trait defined with history: true.
  • defineCommand’s rewind option sets how far back the room may judge the command, as RewindBounds: { maximumSeconds: 0 } judges it at the room’s present, which favors the target.
  • { player, step } in place of the command rewinds to a step a rule has held already, and { player } with no step rewinds by the player’s measured latency. This is for a beam or a swing a system tests on each tick while it reads the player’s held button with readInput.

The reader finds the player’s character with findCharacter(step.world, command.player), and deals a hit with dealDamage(step, target, { amount, source }), which behaviours() provides.

Every command a page sends measures the player’s latency, so a game whose players fire no engine weapon holds them to it all the same. The following plugin, outside/hitscan.ts in the room’s tests, judges each shot with one rewound ray. outsideHitscan.test.ts runs it against a real room, through a wire that delays each way: the ray meets the running dummy where the shooter’s screen showed it, and the same ray on fireNow, held to the room’s present, misses it:

packages/room/test/outside/hitscan.ts
import {
box,
castRay,
createQuery,
defineCommand,
definePlugin,
definePrefab,
defineSystem,
defineTrait,
findEntity,
Phase,
readCommands,
RigidBodyType,
setNextPose,
spawn,
TransformTrait,
vector3,
type AuthoritativeStep,
} from "@spawnite/engine/core";
import { Vector3 } from "three";
// A game's own hitscan gun, built as a creator's plugin is, from the
// engine's public entry alone. The room drives a target dummy across the
// yard. Each shot the shooter's page sends as a command is judged with one
// ray the room casts where the shooter's screen showed the dummy as the
// shooter fired, by the query's `rewind`. A second command holds its view
// step to the room's own, so the same ray meets the dummy where the room
// holds it as the shot lands.
/** Marks the dummy the room drives. */
export const DummyTrait = defineTrait("hitscanDummy");
const dummies = createQuery(DummyTrait);
/** What the room's reader judged of each shot, in order: the command's
* name, and whether the ray met the dummy. */
export const judged: { name: string; hit: boolean }[] = [];
/** How fast the room drives the dummy along +x, in metres a second. */
export const drive = { speed: 0 };
const shot = { from: vector3(), toward: vector3() };
export const hitscan = definePlugin(() => ({
name: "hitscan",
commands: {
// Judged where the shooter's screen showed the target as
// the shooter fired.
fire: defineCommand(shot),
// Held to the room's own step: judged at the present.
fireNow: defineCommand(shot, { rewind: { maximumSeconds: 0 } }),
},
systems: [
defineSystem({
name: "judge",
phase: Phase.Rules,
answers: ["fire", "fireNow"],
run: judgeShots,
}),
defineSystem({ name: "drive", phase: Phase.Rules, run: driveDummy }),
],
}));
const dummy = definePrefab("hitscanDummy", {
traits: [DummyTrait],
body: { bodyType: RigidBodyType.Kinematic },
collider: { shape: box({ size: [0.4, 1.8, 0.4] }) },
});
function judgeShots(step: AuthoritativeStep) {
for (const command of readCommands(step, [
hitscan.commands.fire,
hitscan.commands.fireNow,
])) {
const { from, toward } = command.payload;
const hit = castRay(step, {
from,
direction: toward,
maxDistance: 50,
rewind: command,
});
judged.push({
name: command.handle.name,
hit: hit !== null && hit.entity.has(DummyTrait),
});
command.accept();
}
}
// The dummy's next place, written in place.
const next = new Vector3();
function driveDummy(step: AuthoritativeStep) {
const world = step.world;
if (step.tick === 1) {
spawn(step, dummy, { position: [-4, 0.9, -6] });
return;
}
const found = findEntity(world, dummies);
const at = found?.get(TransformTrait)?.position;
if (!found || !at || drive.speed === 0) return;
setNextPose(step, found, {
position: next.set(at.x + drive.speed / 60, at.y, at.z),
});
}

The game lists hitscan in its plugins. Its page sends a shot with sendCommand(world, hitscan.commands.fire, { from, toward }).

The rules cost the room nothing it can measure next to judging the shot. Judging a shot costs about as much as it did before the rules, and trusting the page costs a fifth less. The rewind history grew from 200 ms of the stream’s sends to a second of them, which a development room’s checkpoints carry. The following numbers were measured on one development machine, each pair in the same minute:

Measure The room judges, with the rules The page judges Before the rules
One shot of three pellets among 4 characters and 40 monsters 54 to 58 µs 45 µs 52 to 55 µs
The same shot with every rule off 61 to 64 µs
Holdfast’s room with 4 bots for 60 s: room CPU a second 45 ms 54 ms
Holdfast’s room with 4 bots for 60 s: memory 268 MB 251 MB
The rewind history in a Holdfast checkpoint 199 KB of JSON, 21 sends the same 5 sends
A Holdfast development room’s longest checkpoint, with 4 bots 18 ms the same 10 ms

The shot’s numbers move with the machine’s load: a quieter run measured 29 to 33 µs with the rules and 34 µs before them. The rules-off row is within that noise of the rules-on row. Holdfast’s bots fire about 90 shots a minute between them, so judging costs its room about 80 µs a second. The difference between the two Holdfast CPU rows is how the two runs played, not the judge. The history keeps what each send changed, and a baseline the oldest sends fold into, so a still world costs it nothing. A development room writes it into each checkpoint, which takes longer as the world grows; a deployed room keeps no recording.

On a phone, the shooter camera holds its lock with a crosshair a finger turns, and weapons() adds three things there:

  • A fire button. Every Weapon draws one in the engine’s row of touch buttons, labelled with its name, a secondary-button weapon’s too. It fires through the crosshair while held, and the finger that holds it may drag to turn the look. touch={{ label, icon }} sets its label and icon, and touch={false} draws none.
  • Auto-fire. A weapon fires on its own while its own shot line, from its muzzle toward the crosshair’s point, rests on a target for 0.1 s, at its rate. It is on for WeaponKind.Instant and off for WeaponKind.Projectile, which leads and arcs; a slow precision weapon sets autoFire: false, as Fortnite’s Auto Fire skips snipers.
  • Aim assist. The look slows over a target near the crosshair, follows a share of its motion and turns toward its edge as the player aims at it. It never moves the shot: the room judges every shot as it judges a mouse player’s.

Both act only on a touch screen, never for a mouse or a pen: while a finger last turned the camera, or on a phone under the touch lock before any input has. A game tunes or turns either off in weapons(), and a weapon lays its own aimAssist over the game’s. The following file, run by phoneShooter.test.tsx, helps toward monsters alone, waits longer before auto-fire, and gives the rail its own way of firing:

packages/engine/test/outside/PhoneShooter.tsx
import { defineTrait, Reach, Weapon, WeaponKind } from "@spawnite/engine";
import { weapons } from "@spawnite/engine/weapons";
/** Marks the monsters the aim assist helps toward on a phone. */
export const MonsterTrait = defineTrait("phoneShooterMonster", undefined, {
reach: Reach.Everyone,
});
/** The assist toward monsters alone, and a longer wait before a weapon
* fires on its own. */
export const phoneShooterWeapons = weapons({
aimAssist: { targets: [MonsterTrait] },
autoFire: { delaySeconds: 0.15 },
});
/** A rifle that fires on its own on a phone, a sling that never does, and a
* rail that keeps to its own button, once per press, with more friction
* while it aims. */
export function PhoneShooterArms() {
return (
<>
<Weapon name="rifle" damage={10} range={40} shotsPerSecond={5} />
<Weapon
name="sling"
kind={WeaponKind.Projectile}
damage={25}
range={30}
shotsPerSecond={1}
speed={20}
/>
<Weapon
name="rail"
damage={60}
range={80}
shotsPerSecond={1}
autoFire={false}
automatic={false}
aimAssist={{ friction: 0.6 }}
touch={{ label: "Rail", icon: "crosshair" }}
/>
</>
);
}

A target meets the shot’s own rule: it has health above 0, and the shot would not pass through it as an ally. By default it also has a body the character controller moves, CharacterCapsuleTrait, and is no other player’s character, so a crate or a door with health is no target. An enemy spawned with health and no capsule, as Depthfield’s are, is no target either: list a trait it holds in targets. Each trait in targets is made with defineTrait and reaches the pages, since the assist runs there.

Nothing the player controls or rides is a target, nor anything between the eye and the character, behind cover from the eye, or past the aiming weapon’s range. The aiming weapon is the first the character holds, and its settings and range drive the assist.

targetPlayers: true counts hostile players’ characters too. It is off, because a desktop browser can emulate touch, and the room cannot tell a finger from a mouse. In a co-op game that costs nobody anything; in a game where players shoot each other, turning it on gives a player who chooses touch a help a mouse player lacks.

Each method runs from 0, off, to 1, under the names Roblox’s AimAssistController gives them: friction slows a drag over a target, tracking follows a share of its motion, and centering turns toward its nearest edge and stops there. weakSpotFriction slows the look over a weak spot, the two margins set how near the crosshair the help reaches, and targets and targetPlayers say what counts. AimAssistOptions gives each option’s default, every one an estimate tuned on a phone.

autoFire: { delaySeconds } sets how long the line rests before the first shot, 0.1 s by default. A value outside its range throws as the game’s plugins are listed, naming the option. aimAssist: false turns the assist off and keeps auto-fire, and autoFire: false does the reverse.

The assist keeps the camera the player’s. A flick faster than 240 degrees a second lets go of the slowdown at once and is never pulled, and every method fades out as a target comes within 1.5 m of the character. Centering never moves the crosshair off a target or one of its zones, so it never drags a head shot down to the body. Together, tracking and centering turn the camera at most 120 degrees a second.

A game that fires its own way reads what the page decided:

  • isAutoFireHeld(world, weapon) answers true while the weapon’s auto-fire holds: the game fires as if its button were held, at the weapon’s rate. A weapon’s muzzle names where its shot leaves the character, which aimShot and auto-fire both read.
  • readAimAssist(world) and the useAimAssist hook give the target, its strength and the friction in force.
  • pauseAimAssist(writer) holds the assist and auto-fire still until the call it returns, as while the character shelters.

The Controls tab shows Aim assist and Auto fire on a touch screen, each on until the player turns it off, as Settings says. They travel with the player from game to game. A game hides either with <HideSetting setting="aimAssist" /> or "autoFire".

Call of Duty Mobile’s Simple mode fires on its own while the crosshair rests on an enemy, and Fortnite’s Auto Fire does the same, skipping snipers, bows and launchers. Roblox’s FPS template turns its AimAssistController on for touch and a pad while a weapon is equipped, and Unreal’s Lyra slows and pulls a stick’s look round a target’s bounds. Unity, Godot and PlayCanvas ship none, and each game builds its own. This one takes Roblox’s three methods and Lyra’s rule that the assist acts only while the player aims. Its margins are angles round what a shot meets, so a skitter and a colossus get the same help for the same thumb error. Its centering stops at the edge where Roblox’s snaps to the middle, and it bends no bullet.

Every registered weapon arms every player until the game says otherwise. A game whose players buy, pick up or swap weapons puts the engine’s HeldWeaponsTrait trait on each character: the names of the weapons the character may fire now. The room refuses a shot from any other under the held rule, and neither the engine’s Weapon nor a room’s bot fires one. holdsWeapon answers the same question for a game’s own trigger.

The trait reads as follows:

  • No trait: the character holds every registered weapon. A game with one weapon, or one that never sets the trait, needs no change.
  • A list: the character holds the weapons it names, and no others. Two names arm two buttons at once, as a Holdfast warden’s gun and lance do.
  • An empty list: the character holds nothing. DisarmedTrait stops every shot too, but a game that takes a gun away keeps DisarmedTrait for a stun or a safe zone.

The room decides what the character holds, because a shot’s consequence is the room’s. A room system writes the whole list, the trait streams to every page, and each page reads what the character holds from its copy of the character. A page never writes the trait: a “buy” or “swap” command asks, and the room’s system checks the player’s wallet or rack before it changes the list.

The scene’s <CharacterSpawn> names the weapons the character starts with, as Roblox’s StarterPack copies its tools into each player’s backpack and Unreal gives a pawn its default inventory: <CharacterSpawn weapons={["pistol"]} />. The room puts HeldWeaponsTrait on each character as it spawns it, so a page that fires before the game’s own systems first reach it fires only those. A <CharacterSpawn> that names none leaves it holding every weapon until a system sets its list.

The following room system runs a gun rack where the character holds one gun at a time. Each character starts with the pistol <CharacterSpawn> names, bought and held. On each “swap” command, the system swaps the character’s gun to one it has already bought, and refuses not-bought for one it has not:

import { addOrSetTrait, addTrait } from "@spawnite/engine/core";
import { createQuery, Not, defineTrait } from "@spawnite/engine/core";
import {
defineCommand,
definePlugin,
ControlledTrait,
findCharacter,
HeldWeaponsTrait,
oneOf,
readCommands,
type AuthoritativeStep,
defineSystem,
Phase,
} from "@spawnite/engine";
/** The guns the character bought, kept through each swap. */
export const RackTrait = defineTrait("rack", (): string[] => []);
const newCharacters = createQuery(ControlledTrait, Not(RackTrait));
function swapGuns(step: AuthoritativeStep) {
const world = step.world;
for (const character of world.query(newCharacters))
addTrait(step, character, RackTrait, ["pistol"]);
for (const command of readCommands(step, rack.commands.swap)) {
const { gun } = command.payload;
const character = findCharacter(world, command.player);
if (!character?.get(RackTrait)?.includes(gun)) {
command.refuse("not-bought");
continue;
}
addOrSetTrait(step, character, HeldWeaponsTrait, [gun]);
command.accept();
}
}
export const rack = definePlugin(() => ({
name: "rack",
commands: {
swap: defineCommand(
{ gun: oneOf(["pistol", "shotgun"]) },
{ refusals: ["not-bought"] },
),
},
systems: [
defineSystem({
name: "swapGuns",
phase: Phase.Rules,
answers: ["swap"],
run: swapGuns,
}),
],
}));

The game lists rack in its plugins, which registers the rack.swap command at the default four a second. Once a buy has put a shotgun in the character’s RackTrait, the page swaps to it with sendCommand(world, rack.commands.swap, { gun: "shotgun" }).

The character’s stats stay on it through the swap, so every card it took raises the new gun as it raised the old one, as Numbers from the shooter’s stats says. A gun’s element is its data, which each of its hits carries.

A game that trusts its players turns the rule off with rules: { held: false } in registerShotSettings, as it turns off any rule. It still sets HeldWeaponsTrait, so the engine’s Weapon fires only the held gun.

The other engines split what a player owns from what the character holds:

  • Unreal’s Lyra sample keeps owned items in an inventory component and equips weapons through an equipment component. Equipping a weapon grants its fire ability, and the server runs only an ability the character was granted.
  • Roblox keeps a player’s tools in the player’s Backpack and moves the equipped tool into the player’s character. Tool.Activated fires only for the equipped tool, and a careful game’s server checks the tool’s parent before it acts on a remote event.
  • Unity, Godot and PlayCanvas leave it to the game.

HeldWeaponsTrait is the second half alone: what the character may fire now. What the player owns, such as a rack, a bag or a loadout, stays the game’s, because games shape it too differently for one engine answer. The trait holds a list rather than one equipped weapon, because a weapon here is bound to a button, and a game fires two buttons at once. With no trait the character holds everything, where the others start with nothing equipped, so the common path stays one <Weapon> and no code.

A weapon’s numbers are its own base. stats names, for each number, the shooter’s stats that raise it, as a WeaponStats. The room lays each named stat on the weapon’s own number by the stats formula: the stat’s base and its flat modifiers add to the number, and its percent and more modifiers scale it. So one card raises every weapon that names its stat, each from that weapon’s own base, and a player who swaps guns keeps every card, because the modifiers live on the character and not on the gun.

A rifle on the primary button and a rail on the secondary, both naming damage:

import { PointerButton, Weapon, type WeaponStats } from "@spawnite/engine";
const gunStats: WeaponStats = { damage: "damage", shotsPerSecond: "fireRate" };
export function Guns() {
return (
<>
<Weapon
name="rifle"
damage={10}
range={40}
shotsPerSecond={5}
stats={gunStats}
/>
<Weapon
name="rail"
damage={40}
range={60}
shotsPerSecond={0.75}
stats={gunStats}
button={PointerButton.Secondary}
/>
</>
);
}

A card that adds { percent: 0.25 } to the character’s damage stat makes the rifle hit for 12.5 damage and the rail for 50 damage. A game whose players each hold one gun at a time registers every gun with registerWeapon and names the one the character holds in HeldWeaponsTrait. Holdfast registers the three guns of its rack and its lance the same way: a warden holds one gun on the left button, and the lance on the right once a card gives it. The character’s stats stay on it through a swap.

The following rules hold for every weapon:

  • A number the weapon names no stat for stays its own, whatever the character’s stats. A rail that should not take a pellet card leaves pellets out.
  • A list lays several stats on one number: one every gun shares, and one for this gun alone, such as the stat its own tiers raise: damage: ["damage", "scattergunDamage"]. A gun’s perk, such as a ricochet, is the game’s own system reading the gun’s hits.
  • The shooter’s stat need not be declared; one the shooter lacks adds nothing. Its min and max are not read, since they are in no one weapon’s units.
  • pellets and pierce are whole counts, rounded, with at least one pellet. No number falls below zero.
  • pellets, spread and pierce shape an instant weapon’s pull. A projectile hits the first target in its path, so they change nothing for it. Extra pellets on a weapon with no spread fire down one line, each hitting the same target.
  • speed is a projectile’s alone: its own speed, or 20 m/s where it names none, raised by the stats it names, such as speed: "velocity" for a card that makes a grenade fly faster. An instant shot has no flight, so it changes nothing there.
  • zoneDamage multiplies the multiplier of the hit zone a hit strikes: its own zoneDamage, or 1 where it names none, raised by the stats it names, such as zoneDamage: "headshots" for a card that makes every weak-spot hit deal a quarter more. A hit on the body deals the weapon’s damage whatever it is.

Holdfast’s guns and lance share each warden’s damage and fire-rate stats, and each gun of its rack also names gun stats that only its upgrade tiers raise. It registers its weapons with registerWeapon in its siege plugin’s setup, on the room’s world and each page’s, since it fires them from its own trigger. Its room system hands each warden the gun the warden bought, and the lance once the warden takes its card.

Unreal’s Gameplay Ability System keeps the attributes on the character and the weapon’s base damage in its ability or data asset, and a damage calculation combines the two. Roblox games keep each weapon’s numbers in a module and multiply them by the player’s buffs. Unity, Godot and PlayCanvas leave it to the game. Games such as Brotato, Risk of Rain 2 and Call of Duty Zombies apply a player’s damage and fire-rate bonuses to whichever weapon the player’s character holds. Weapon follows the same split: the base on the weapon, the bonuses on the player, combined by the formula the player’s other stats already use.

An entity declares the parts of it a shot strikes for more or less damage, such as a head or a glowing core, with the engine’s HitZonesTrait trait. Each HitZone is a sphere round at, or a capsule from at to to, with a radius, a name its hits carry and a multiplier on the weapon’s damage. A monster’s prefab declares its head in one line:

packages/engine/test/outside/ghoul.ts
import { definePrefab, HealthTrait, HitZonesTrait } from "@spawnite/engine";
export const ghoul = definePrefab("ghoul", {
traits: [
HealthTrait({ current: 30, maximum: 30 }),
HitZonesTrait([
{
name: "head",
multiplier: 2,
at: { x: 0, y: 1.4, z: -0.2 },
radius: 0.25,
},
]),
],
});

A point is in the entity’s own frame: metres from its feet, with its front along -z, the way an entity faces at rest. The zones turn with its TransformTrait.rotation. A point is an { x, y, z } record or a Vector3.

A zone whose multiplier is above 1, such as a head at 2x or a glowing core, is a weak spot: the page draws a gold marker where a shot strikes one, and the aim assist slows the look a little more over it. A zone at 1x or below, such as armour, is no weak spot. isWeakSpot answers it for a zone.

A shot’s ray hits the entity where it meets its body or one of its zones, whichever it meets first, so a head that pokes out over the body’s capsule is hit. The hit takes the name of the first zone the ray meets anywhere along its line, even behind the body’s front, and deals the weapon’s damage times that zone’s multiplier, times the weapon’s zoneDamage as the shooter’s stats raise it. A ray that meets no zone hits the body at the weapon’s damage.

The zone says how much more a part takes, and the weapon says how much more it makes of that, so a monster’s head deals double to every gun and a sniper’s zoneDamage: 1.5 makes it triple, all in one hit whose number shows the whole of it. Destiny splits it the same way, a precision multiplier per weapon on the enemy’s weak spot, as Borderlands lays a critical-damage stat on its guns’ critical hits. Every kind of hit judges zones alike: the room’s judgement of an instant shot, rewound to where the target stood and faced on the shooter’s screen; each target a trusted page names; a projectile’s hit; and a page with no room.

The stream carries the zones, so the room and every page test the same shapes against the same place and turn, and the page’s marker agrees with the room’s verdict. The zone reaches the game as the hit’s zone, and each target in a ShotResult carries it too, with the page’s number for the shot, which sendShot returned.

The room runs no animation, so a zone does not follow a bone. Size each zone to hold its part through the clips the entity plays: its walk, its strike and its flinch. A capsule along the line a head sways on keeps a zone close to the head where a sphere round the whole sway would reach past it. <Landscape hitZones> draws every zone over its model to size them against it, and on a development page window.__GAME_HIT_ZONES__(true) turns them on, which spawnite play eval reaches.

The other engines judge a zone against an animated body:

  • Source’s server poses a character’s bones from its stored animation state for each rewound trace, and each hitbox names a hitgroup, a head with four times the damage among them.
  • Unreal’s hit result names the bone of the physics asset’s body it struck. A dedicated server leaves the pose alone unless a game ticks it, so shooters built on Unreal commonly let the client trace and have the server check the hit loosely.
  • Unity, Godot and PlayCanvas leave zones to the game, with a collider per part; Photon Fusion’s hitboxes follow animation only where the game poses them before its capture.
  • Roblox’s raycast returns the part it hit, such as Head.

A zone here is fixed in the entity’s frame instead, as a platform whose server knows only a reference pose does. The room runs the same test as the page, costs nothing past the zones of a target a ray reaches, and a replay continues it exactly. The price is that a zone sized for a whole clip is a little larger than the part at any one moment.

Each target a shot hits takes one DamagedEvent per hit, one for each pellet, for an instant shot and a projectile alike. Two players’ hits on one monster in one step are two events, in the order the room deals them. A hit the target refuses, such as one on an invulnerable target, is a DamageRefusedEvent instead, as Health says. The event’s record is a Hit with at, and carries the following:

  • amount: the health the hit was asked to take, its zone’s multiplier included.
  • healthTaken: the health it took, never more than the target had.
  • source: the shooter’s character.
  • instigatorPlayer and instigatorTeam: the player and the team key the hit was judged by, which Crediting a kill reads.
  • weapon: the weapon’s name, a string, never its entity.
  • zone: the name of the hit zone it struck, its multiplier already in amount; null for the body.
  • data: the weapon’s data, the game’s own record for each of its hits, such as a pellet’s dose of an element. null for a weapon with none.
  • at: where the target stood as the hit landed, so a damage number shows after a killing blow; the origin for a target with no position.

data is the same for every hit of the weapon. What depends on the shooter, such as the shooter’s element, a game reads off source. A game types data once by adding hitData to the engine’s Register, as it types its levels; without it, data is any record:

packages/engine/test/register/elements.ts
export enum Element {
Storm = "storm",
Frost = "frost",
}
declare module "@spawnite/engine" {
interface Register {
hitData: { element: Element; dose: number };
}
}

From then on a weapon’s data, dealDamage’s data and each hit’s data take only that shape. A system in the room reads the hits, since a hit’s consequence is the room’s:

packages/engine/test/register/chill.ts
import {
addOrSetTrait,
DamagedEvent,
definePlugin,
defineTrait,
readEvents,
type AuthoritativeStep,
defineSystem,
Phase,
} from "@spawnite/engine/core";
import { Element } from "./elements";
export const ChillTrait = defineTrait("chill", { amount: 0 });
/** Adds each Frost hit's dose to the chill of what it struck. */
function chillOnHit(step: AuthoritativeStep) {
for (const { entity, record: hit } of readEvents(step, DamagedEvent)) {
if (!entity || hit.data?.element !== Element.Frost) continue;
const amount = (entity.get(ChillTrait)?.amount ?? 0) + hit.data.dose;
addOrSetTrait(step, entity, ChillTrait, { amount });
}
}
export const chill = definePlugin(() => ({
name: "chill",
description: "A Frost hit chills what it strikes by its dose.",
systems: [
defineSystem({
name: "chillOnHit",
phase: Phase.Rules,
run: chillOnHit,
}),
],
}));

A game’s own damage, such as a chain of lightning, carries the same fields: dealDamage(step, monster, { amount, source, weapon: "chain", data }).

In a room, every page hears each hit in the delta after it lands, each source as its own copy of the shooter’s character, one entry per hit. On the binary stream, a hit weighs about 61 bytes, measured with an element’s name and a dose as data and a team key in its credit. So four players landing 120 hits a second between them add about 7 KB a second to each page’s stream; longer data weighs more.

data holds numbers, strings, booleans, lists and records of them, and reaches a page as the same JSON the room held: a colour as [1, 0, 0] stays that list. ShotJudgedEvent stays the stream a tracer draws: where each instant shot went. It is an event on the world, one event a shot, so a view hears each shot once with useEvent. A projectile draws as its own entity and adds no result there.

Unreal’s ApplyDamage names an instigator, a damage causer and a damage type class, and its Gameplay Ability System carries each hit as an effect spec with a context the game extends. A hit here holds the same: instigatorPlayer and instigatorTeam name the instigator, source the entity that dealt it, weapon the name of what dealt it, and data the context. Roblox’s Humanoid:TakeDamage takes the amount alone, and games tag the attacker on the humanoid themselves; Unity, Godot and PlayCanvas leave damage to the game.

Both. The room holds every shot to the weapon, and the page fires it and draws the shot. The arena’s scene carries a rifle on the primary button and a sling on the secondary:

import { PointerButton, Weapon, WeaponKind } from "@spawnite/engine";
export function Armoury() {
return (
<>
<Weapon name="rifle" damage={10} range={40} shotsPerSecond={4} />
<Weapon
name="sling"
kind={WeaponKind.Projectile}
damage={25}
range={30}
shotsPerSecond={1}
speed={20}
model="stone"
button={PointerButton.Secondary}
/>
</>
);
}