Health
Health gives an entity a pool of hit points, starting full. A player’s character is a character a player may control, every one <CharacterSpawn> spawns, whether or not the player controls it now, so the character waits for its respawn while the player flies a drone. A kart is no character, and an NPC no player may control, so a death removes them unless they carry a respawn. A view reads the local player’s character with useCharacter().
Its props are in HealthProps.
dealDamage(step, entity, damage) takes an entity’s health down, never below zero, and returns why it applied nothing, or null. Damage is an outcome, so its first argument is the room’s step, or the authority useAuthorityEffect hands a logic component, as Where a system runs describes. An amount below 0, or no finite number, throws, naming dealHealing as the way to give health back.
The step downs the entity at zero and removes it the step after. An entity with <Respawn> is not reaped: it goes down and stands again. A player’s character is not reaped either: it goes down, with the DownedTrait trait, stays in the world, and respawns a few seconds later unless the game turns that off.
damage is a Damage, whose fields past amount are optional:
amount: the health to take, a finite number from 0.source: the entity that dealt it, such as the shooter’s character. The entity’sDamageSourceTraitkeeps the last one.weapon: the name of what dealt it. A weapon’s hit carries the nameregisterWeapongives it, and a game’s own damage takes any name, such as"chain".zone: the hit zone it struck, its multiplier already inamount.data: the game’s own record for the hit.instigator: who is behind the hit, anInstigatorasreadInstigatorread it when the hit was made. The hit is judged and credited by the team it was made for. A weapon’s projectile keeps the one read at its launch by itself. A thrown object a game spawns itself keeps the one read at the throw and passes it as it lands. Left out, it issource’s at the call, andnullnames no one.friendlyFire: this hit’s own friendly fire over the world’s, as a weapon’sfriendlyFirepasses it.
An ally of whoever is behind the hit takes no damage while friendly fire is off, DamageRefusal.FriendlyFire. So with no teams(), one player’s hit on another player’s character applies nothing. An entity with InvulnerableTrait takes none either, its own hits included, DamageRefusal.Invulnerable; an invulnerable ally’s refusal is FriendlyFire.
Each call that applies emits one DamagedEvent on the entity, which the weapon page says how to read. An entity with no health takes the hit and its event, and loses none.
Its record holds amount as asked, and healthTaken, the health it took, never more than the entity had. A hit on an entity already at zero, down or not, still applies, and its DamagedEvent reads a healthTaken of zero. So a thorns rule reflects a share of healthTaken, with no other check. A dead boss reflects nothing, and its killing blow reflects what it took.
Its credit is source, and instigatorPlayer and instigatorTeam, the player and the team key the hit was judged by, as Crediting a kill says.
A refused call changes nothing on the entity: no health, no DamageSourceTrait, and no pause of its regeneration. It emits one DamageRefusedEvent on the entity in place of DamagedEvent. Its record holds amount as asked, the credit, weapon, zone and data as given, at, where the target stood, and reason, the DamageRefusal. So a rule that counts hits, or a view that shows “Immune” at at with useFloatingText, reads every hit, applied or not. useFloatingText draws only where the scene mounts one <FloatingText />.
A refusal’s replication is EventReplication.Cosmetic, since it changes nothing a page keeps: the room’s systems read every one, and a page far behind drops it, so a count belongs in the room. A refusal stops only the damage: an ability’s strike on an invulnerable enemy still slows it, while an ally’s carries nothing.
InvulnerableTrait is the room’s alone: the stream does not carry it, so a page cannot read it. A shield that every page draws reads a trait of the game’s own, made with defineTrait, which the room sets beside InvulnerableTrait. A view or the game’s HUD reads such a trait with useTrait(entity, Trait), and finds an entity, such as the boss, with useQueryFirst(BossTrait), as Logic and views says.
A game that keeps its characters’ health in a trait of its own spares an InvulnerableTrait character too, as Holdfast’s wardens do. A room started with ROOM_INVULNERABLE=1 gives every player’s character it, for spawnite play profile --invulnerable, the way Unreal’s bCanBeDamaged and Roblox’s ForceField stop damage. Each hit dealDamage refuses there shows in the dump as a DamageRefusedEvent; a game that spares the character in its own damage, as Holdfast does, emits what that game emits.
dealHealing(step, entity, { amount, source }) gives health back, never past the maximum. It is an outcome too, so it takes the same authority as dealDamage. Each call emits one HealedEvent, { amount, source }, on the entity, so a view draws a rising number and a game credits the healer. Its amount is the heal as asked, which can be more than it restored where the entity stood near its maximum, as a hit’s amount can be more than its healthTaken. A view reads HealedEvent as it reads DamagedEvent, with useEvent, as the weapon page says, and useFloatingText draws the number over the entity.
A downed character is healed and stays down until the game removes DownedTrait, as a revive does. An amount below 0, or no finite number, throws, naming dealDamage as the way to take health off, and an entity with no health throws too. A potion’s heal is one of these, by the character who drank it. changeResource does not change health: healthResource is a type error there, and a key that holds it throws, so a page in a room cannot change an outcome. Unreal’s ability system applies a heal as a gameplay effect beside damage, and Roblox leaves it to a script that sets Humanoid.Health; here a heal is its own outcome with its own event, as damage is.
useHealth(entity) reads an entity’s { current, maximum } for a bar or a label. It returns undefined while the entity has no Health, so the caller chooses whether to hide the bar or draw it full.
When it dies
Section titled “When it dies”The reap, behaviours.reapDead, downs an entity whose health has reached zero, with DownedTrait, and emits DiedEvent on it. It does so in the same step for a hit dealt before the reap, and in the next step for one dealt after it, such as a projectile or an ability in a later system. A system that reads DiedEvent after the reap reads it in the step it is emitted, and one before it reads it the next step, as every event is read. The step after the reap, it removes the entity, unless it is a player’s character or has a respawn. Between the two, the entity keeps its traits but does nothing: no ability targets it, a projectile passes through it, a chaser stops, and it fires no shot. So every game system reads its death and its traits, such as a boss’s mark or a monster’s loot table, before the entity goes. Roblox fires Humanoid.Died the same way, and Unity’s Destroy and Godot’s queue_free hold an object until the frame ends for the same reason.
DiedEvent carries the credit of the hit that first took the health to zero, source, instigatorPlayer and instigatorTeam, and cause, a DeathCause. The cause is DeathCause.Hit for every death the reap finds. It is DeathCause.TeamChange for a player’s character that characters() downs as the player’s team changes, with no credit, as Teams says. DeathCause.FellOutOfWorld is a player’s character that fell below the world, with no credit, as When a character falls out of the world says. A game that drops loot or counts lives skips that cause. A later hit in the same step does not take the credit, and a death no hit dealt, such as a game setting the health to 0 itself, credits no one. source is null too where the killer is already gone.
A player’s character and an entity with a respawn get DiedEvent once per life: a hit while it lies down fires nothing, and the next death after it stands again fires it again. An entity the game downed itself, such as a hostile it stunned at full health, dies as any other does when its health reaches zero. Healing an entity above zero before the step reaches it, or a game setting its health above zero, means it never dies, and a later death names only a hit dealt after that. Healing it after it died does not bring it back: the step after still removes it, unless the game takes DownedTrait off first, as a revive does.
A game reads DiedEvent in a system with readEvents, and a page hears it with useEvent(DiedEvent, …). In a room the room emits it, and every page that holds the entity hears it a send later, with the dead entity and its killer still standing in the page’s world. A page keeps an entity the stream removed until its next step has read the events that name it, as Events says. So a kill feed, a death animation or a drop on a page reads what died, where it fell and who killed it. A game that counts deaths counts them in a system on the room and streams the count, as the following kill count does. It runs on the room, and the engine’s tests run it against a real room:
import { addTrait, definePlugin, defineTrait, DiedEvent, readEvents, setTrait, type AuthoritativeStep, defineSystem, Phase,} from "@spawnite/engine/core";
// A kill count, built as a creator's plugin is, from the engine's public// entry alone: the room adds one to a player's character's count for each// death the character dealt the lethal hit of, and the stream carries the// count to every page.
/** The kills a player's character has made; the stream carries it. */export const KillsTrait = defineTrait("outsideKills", { count: 0 });
export const kills = definePlugin(() => ({ name: "kills", onCharacterSpawn: ({ writer, character }) => { addTrait(writer, character, KillsTrait); }, // No runsOn: the room alone counts, and a game played alone is its // own room. systems: [ defineSystem({ name: "count", phase: Phase.Rules, run: countKills, }), ],}));
function countKills(step: AuthoritativeStep) { for (const { record } of readEvents(step, DiedEvent)) { const killer = record.source; const tally = killer?.get(KillsTrait); if (killer && tally) setTrait(step, killer, KillsTrait, { count: tally.count + 1 }); }}Crediting a kill
Section titled “Crediting a kill”A hit and a death credit who dealt them three ways:
sourceis the entity that dealt the hit, such as the player’s character. It readsnullonce that entity is gone.instigatorPlayeris the player behind the hit as it was judged. It stays once the player’s character is gone, and readsnullfor an NPC’s hit, or once the player left the room.instigatorTeamis the key of the team the hit was judged for,nullfor none, andfindTeamByKeyturns it back into its team. It stays once the player left.
So a kill feed names the killer by instigatorPlayer, and a score by team reads instigatorTeam, as Teams shows. A player who left takes their name with them: a feed that must name the departed player keeps the name as the death lands.
readDisplayName(entity) reads a name for the feed: a player’s name, a character’s as its player’s, and an NPC’s own. So “Ada killed Bo” is readDisplayName(record.instigatorPlayer) and readDisplayName(event.entity), and a view reads the same with useDisplayName. The player behind a character is readInstigator(world, character).player on every world. findCharacterPlayer(world, character) answers it on the room, but on a page only for the local player’s own character, since the tie from a player to their character reaches the player’s page alone. A grenade that kills after its thrower switched teams credits the team the thrower threw it for, the team its hit was judged by. Damage over time is credited tick by tick, as Friendly fire judges it. Unreal’s damage names the instigating controller the same way, which outlives the pawn.
A match won on a boss’s death reads DiedEvent the same way, as the Match page shows.
When a character runs out of health
Section titled “When a character runs out of health”A player’s character at zero health goes down, waits 5 seconds, and comes back at the point it spawned at with full health, whether <CharacterSpawn>, a room or spawnCharacter spawned it. In a room the player’s connection stays open throughout, and the player’s page shows the seconds left. A game needs no code for this. Roblox does the same with its Players.CharacterAutoLoads and Players.RespawnTime, 5 seconds by default. Unreal’s game mode restarts a player’s pawn when the game calls RestartPlayer, and Unity, Godot and PlayCanvas leave it to the game.
To change it, set respawn on the scene’s <CharacterSpawn>:
import { CharacterSpawn, RespawnPlace } from "@spawnite/engine";
export function Character() { return <CharacterSpawn respawn={{ seconds: 3, at: RespawnPlace.Fallen }} />;}secondsis how long the character stays down first: 5 by default, and 0 brings it straight back.atis where the character comes back:RespawnPlace.Spawn, the point it spawned at, by default;RespawnPlace.Fallen, where it fell; or a point the game names, such as[0, 2, 10]. Where another character stands on the point, it comes back on the nearest free place round it, as Many players at one point says.
One player’s own point, such as the last checkpoint the player’s character touched, is setRespawnPoint, which stands over at, as The player’s respawn point says.
In a room <CharacterSpawn>’s respawn holds for every player’s character. Each character carries it as its RespawnTrait trait, which the dump of a room or of a game played alone shows as respawn, and which the room streams to the character’s player’s page alone. The trait holds seconds, point, and inPlace where the character comes back where it fell. While the character waits, it keeps DownedTrait and carries RespawningTrait, whose seconds is the whole wait and whose respawnTick is the tick the character stands on; a dump shows it as respawning. readRespawnRemainingSeconds(character) reads the seconds left from it, as the respawn screen does. The character walks, jumps and fires nothing while it is down.
A respawn at a point is a teleport at rest. Every page cuts to the character there rather than drawing it across the map, and the player’s own page’s camera starts afresh, as on any teleport. A push it was under ends, and a knockback it went down in does not carry over. A respawn where it fell keeps its pose and motion. It is the same entity either way, so every trait the game gave it stays on the character. Unity and Godot cut a teleported body the same way.
Where the point overlaps a wall or a fixed body too deep to push the character out of, it still stands there, alive and marked with StuckTrait, and its next move frees it as far as it can. The world logs a warning that names the point, once per character and point. Unreal’s default pawn fails to spawn instead, and Roblox lifts the character above what blocks the spawn. Place a respawn point clear of walls. For a brand-new body in place of the old one, as Roblox’s LoadCharacter makes, a game calls spawnCharacter.
To own the death flow, such as a revive by a teammate, turn respawn off with respawn={false}. The player’s character then stays down, the player’s connection stays open, and the game gets the character up with respawnCharacter(step, character, { position, rotation }), the call the engine’s own respawn makes. It stands the same entity at full health, off the ground, at position at rest or where it fell, facing rotation or as it fell, then runs each plugin’s onCharacterRespawn, as Unreal’s RestartPlayer does. It answers isClear: false where the point blocked it, so a game can pick another. A game can also give it health above zero and remove DownedTrait itself; removed at zero, the next step downs it again. A game that gets the character up while it waits to respawn ends the wait. Depthfield turns respawn off for its death screen. Holdfast keeps its wardens’ health on a trait of its own, so the engine never downs a warden, and turns respawn off as well.
A game that owns the death flow decides what a fall does too. Depthfield and Holdfast stand a character that falls out of the world at the spawn with OutOfWorldEffect.Respawn, as the next section says, so a fall never leaves the character down outside their own flow.
While the player’s character waits, Game draws the seconds left over the game. A game draws its own screen, or none, with Game’s respawnScreen.
When a character falls out of the world
Section titled “When a character falls out of the world”A living character whose feet go below the scene’s killBelowHeight, -500 m unless definePhysics sets another, gets FellOutOfWorldEvent on the step the character crosses it. The event’s height is where the character’s feet stood; a dynamic body’s is where its centre stood. A system that reads the event and puts the character back above the height with teleport(step, character, { position, keepVelocity: false }) keeps the character, as it keeps a dynamic body. With Respawn, below, that catch comes after the player’s page has returned the character. Any system outside the physics phase runs in time. Otherwise, at the next step:
- A player’s character does what
characters({ outOfWorld })says. - Any other character, an NPC, is destroyed as a dynamic body is, whatever its health or
<Respawn>.
outOfWorld takes an OutOfWorldEffect:
Die, the default: the character goes down with no killer, andDiedEventcarriesDeathCause.FellOutOfWorld. Its respawn brings it back as from any death, after its wait, which starts on the step after the character goes down.Respawn: the character stands at once where its respawn would stand it, alive, at full health and with no death, and each plugin’sonCharacterRespawnruns. That is the player’s respawn point where one holds, such as the last checkpoint the character touched, else the character’s spawn. An obby or a platformer whose players never die takes it. The player’s page stands the player’s own character at its respawn’s own point on the room’s tick too, so the return shows at once. The room’s word places every other return: to the player’s respawn point, to a team’s or a match’s spawn, or of a character at zero health. A game that catches falls itself takesNone; withRespawn, the room warns once.None: the engine does nothing to the character and it keeps falling. A game that catches falls its own way reads the event.
Roblox’s Workspace.FallenPartsDestroyHeight, -500 by default, destroys a character’s parts below it, which kills the character, and the respawn follows after Players.RespawnTime. Unreal’s KillZ calls FellOutOfWorld on any actor, a pawn included, which a game overrides to keep it. Unity, Godot and PlayCanvas leave the check to the game.
A respawn never stands the character below the height again. The player’s respawn point set below it is passed over for the character’s spawn, and so is a point a spawnCharacter’s props name, each with one warning. A respawn where the character fell, RespawnPlace.Fallen, stands the character at its spawn instead. A <CharacterSpawn> or a spawn point below the height throws as the scene mounts, and a deployed room leaves such a spawn point out. With None, none of this holds, so a game with a deeper catch of its own spawns where it likes. A character attached to a body is let go as the fall takes the character, so its return holds.
Other cases:
- A character already down falls on until its respawn, with no second death.
- A hit that took the character to zero earlier in the step keeps the kill, credited: the reap downs the character before the fall does.
InvulnerableTraitdoes not stop a fall, as Roblox’sForceFielddoes not.- With
respawn={false}andDie, the character stays down for the game’s own flow, as from any death. - A world that declares no body steps no physics scene, so nothing in it falls out.
- A game that wants a shallow catch for its players and deep water for its bodies sets
Noneand checks the height itself.
When anything else runs out of health
Section titled “When anything else runs out of health”Any other entity at zero health goes down for a step, then the step removes it, as When it dies says. To keep one in the world, such as a monster that comes back, give it <Respawn> beside its <Health>:
import { Entity, Health, Respawn, type EntityProps } from "@spawnite/engine";
export function Wolf({ position }: Pick<EntityProps, "position">) { return ( <Entity model="wolf" animation="idle" position={position}> <Health maximum={60} /> <Respawn seconds={20} clip="death" /> </Entity> );}Its props are in RespawnProps:
secondsis how long it stays down: 5 by default, as a player’s character’s wait is.clipnames the clip its model plays once as it goes down and holds until it stands, asplayClipholds one. With none, its model keeps playing the animation it loops.
At zero health the entity goes down on the next step, as a player’s character does:
- It carries
DownedTraitandRespawningTrait, and its health stays at 0. - No ability targets it, and a projectile passes it to what stands behind.
- A chaser stops where it fell, and the other chasers walk over it. A game’s own system that moves an entity leaves out one with
DownedTrait, as it would a downed character. - After
secondsit stands where it fell, at full health, and its held clip ends.
It keeps its TargetableTrait and its collider while it is down. A game that gets it up first, with health above zero and DownedTrait removed, ends the wait and the held clip. In a room, the room runs the respawn, and every page draws the fall and the return from the stream.
<Respawn> is for an entity a scene places. A player’s character’s respawn is <CharacterSpawn>’s respawn. Outside an <Entity>, <Respawn> throws where it renders and names that prop. Among <CharacterSpawn>’s children that is on a page, once the character’s model is drawn: a room or a headless run draws none of <CharacterSpawn>’s children, so there it does nothing. For a placed entity, a respawn at another spot is not built: a game spawns a new entity there instead, as Spawn one at runtime shows. A player’s character stands again at any spot with respawnCharacter, above.
Roblox respawns a player’s character and leaves a monster to a script that clones its model. Unity, Unreal, Godot, PlayCanvas and Phaser leave a monster’s death and return to the game. The engine ships it, because a creator who asks for wolves that come back should need no code for it.
Max health is a stat
Section titled “Max health is a stat”maximum is the base of the entity’s maxHealth stat, which <Health> and the <CharacterSpawn> component declare with a min of 1. maxHealthStat names it. A modifier on it raises or lowers the cap, as an upgrade, an item or a curse would:
import { addStatModifier, maxHealthStat, removeStatModifiers, useAuthorityEffect, useEntity,} from "@spawnite/engine";
export function Amulet() { const wearer = useEntity(); useAuthorityEffect( (authority) => { addStatModifier(authority, wearer, maxHealthStat, { source: "amulet", flat: 20, }); return () => removeStatModifiers(authority, wearer, "amulet"); }, [wearer], ); return null;}Each step sets maximum to the stat’s resolved value, then clamps current:
- When the cap falls below
current,currentfalls to the cap. - When the cap rises,
currentstays where it is. A game that wants the new points filled heals the entity itself.
So the devtools inspector’s Health card has no maximum slider on an entity with the stat, since the next step would overwrite an edit. The inspector’s Stats card slides the maxHealth base instead, and the modifiers still apply over it.
A save keeps the stat’s base as maximum, never a buff over it, and keeps current as it was, which a saved modifier may hold above that base. The first step after a load caps current at the resolved maximum, so a save whose current is past every cap still loads.
Unreal’s Gameplay Ability System pairs Health with a MaxHealth attribute in the same way, and leaves the current value where it is when the cap rises. In Unity, Godot and PlayCanvas, games and add-ons write the same pair.
Health is a resource
Section titled “Health is a resource”Health is the resource healthResource, the engine’s own, so its bar and its regeneration work as mana’s and stamina’s do. Damage, death, the downed character, hit zones and the save stay Health’s own.
<ResourceBar resource={healthResource}> draws an entity’s health in the theme’s health tone, var(--color-health-fill), under the label “Health”. label names it otherwise, and showValue reads 30 / 120 beside it:
import type { Entity } from "@spawnite/engine/core";import { healthResource, ResourceBar } from "@spawnite/engine/resources";
export function WolfHealth({ wolf }: { wolf: Entity }) { return ( <ResourceBar entity={wolf} resource={healthResource} label="Wolf health" showValue /> );}Health does not regenerate unless a game registers a regen for it, as Unreal’s and World of Warcraft’s games each choose their own. Register it with registerHealth in a plugin’s setup, with regenDelaySeconds for the seconds it waits after each hit, and a color or label where the theme’s do not fit:
import { definePlugin } from "@spawnite/engine";import { registerHealth } from "@spawnite/engine/resources";
export const healing = definePlugin(() => ({ name: "healing", setup: (_world, writer) => registerHealth(writer, { regen: 5, regenDelaySeconds: 4 }),}));registerHealthtakes nomaximum:<Health maximum>and<CharacterSpawn>’shealthgive health and set its maximum, so leavehealthResourceout of<CharacterSpawn>’sresourcesand of<Resource>.- A
healthRegenstat on an entity takes the place ofregenfor it, as an item of regeneration would. - An entity at zero never regenerates: a downed character waits for its respawn or the game.
- An ability’s
costcannot name health, since a cast holds its cost back and health holds no reserve. An ability that spends health deals it to the caster withdealDamagein its effect.
A bar over its head
Section titled “A bar over its head”To hang the bar over the entity, as a boss’s or a monster’s is, put it in a Panel anchored to the entity, <Panel anchor={Anchor.Above}>, inside the <Entity> beside its <Health>. The Panel follows the entity and faces the screen, and useEntity() names the entity for the bar. The engine’s tests mount this boss and read its bar before and after a hit:
import { Anchor, BarSize, Entity, Health, Panel, PanelVariant, useEntity, type EntityViewProps,} from "@spawnite/engine";import { healthResource, ResourceBar } from "@spawnite/engine/resources";
function BossHealthBar() { const boss = useEntity(); return ( <Panel anchor={Anchor.Above} maxDistance={60} variant={PanelVariant.Glass} > <ResourceBar entity={boss} resource={healthResource} label="Yeti king health" size={BarSize.Large} /> </Panel> );}
function YetiKingView(_: EntityViewProps) { return ( <mesh> <boxGeometry args={[2, 3, 2]} /> <meshStandardMaterial color="#dfe8f0" /> </mesh> );}
export function YetiKing() { return ( <Entity position={[0, 0, -30]} view={YetiKingView}> <Health maximum={500} /> <BossHealthBar /> </Entity> );}A Billboard holds meshes rather than HTML, so a bar built from its meshes draws neither the ResourceBar’s hit nor the theme’s colours.
Where it runs
Section titled “Where it runs”Server. Health has a consequence: it can end the entity.
import { Entity, Health, Views, type EntityProps } from "@spawnite/engine";
export function Yeti({ position }: Pick<EntityProps, "position">) { return ( <Entity position={position}> <Health maximum={30} /> <Views> <mesh position={[0, 0.9, 0]}> <capsuleGeometry args={[0.5, 0.8]} /> <meshStandardMaterial color="white" /> </mesh> </Views> </Entity> );}