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

Teams

teams() puts each player on a team. List it in the game’s plugins, and import its names from @spawnite/engine/teams. The engine’s own team names, the Team type, findTeam, isTeammate, isAlly, readInstigator, isFriendlyFireEnabled, TeamChangeCause, TeamChangedEvent and DamageRefusal, come from @spawnite/engine/core, and from @spawnite/engine beside the views. The plugin’s handles hang on its factory, as every plugin’s do: teams.commands.switch and teams.systems.takeSwitches. The plugin balances each joining player onto a team, takes the player’s request to switch, and answers the team question the engine asks: damage, weapons, chase, abilities and nameplates all follow the teams without a line of your own.

With no teams() listed, every player is on every other player’s side, as in a co-op game: one player’s shot passes through another, and a monster with no team fights them all. A game with a free-for-all says so, as A free-for-all shows.

Roblox’s Teams service is the closest match: teams a game declares, a join to the smallest team marked AutoAssignable, and Team:GetPlayers(). Counter-Strike and Team Fortress 2 add the rest of what this plugin does: a switch the server may refuse, a cap on the gap between teams, and friendly fire off by default.

Declare each team at module scope with defineTeam, and list the teams in teams(). Each player who joins goes to the team with the fewest players; a tie goes to the team declared first:

packages/room/test/outside/teams/twoTeams.ts
import { characters } from "@spawnite/engine/characters";
import type { SetupWriter } from "@spawnite/engine/core";
import { placeSpawnPoints, type Authority } from "@spawnite/engine/core";
import { defineTeam, setTeamSwitching, teams } from "@spawnite/engine/teams";
import { Vector3 } from "three";
// Two teams with auto-balance: each player who joins goes to the smaller
// team and spawns at the player's team's base, a player may switch
// between rounds, and a teammate's shot passes through
// the player's character.
export const red = defineTeam("red", { name: "Red", color: "#e5484d" });
export const blue = defineTeam("blue", { name: "Blue", color: "#3e63dd" });
/** Players who watch: never balanced, never auto-assigned. */
export const spectators = defineTeam("spectators", {
balanced: false,
autoAssignable: false,
});
export const plugins = [
characters(),
teams({
teams: [red, blue, spectators],
switching: { cooldownSeconds: 10, maxPlayerDifference: 1 },
}),
];
/** Each team's base, in its own half. */
export const redBase = [new Vector3(-20, 0, 0), new Vector3(-20, 0, 4)];
export const blueBase = [new Vector3(20, 0, 0), new Vector3(20, 0, 4)];
/** The scene places each base: a player spawns, and respawns after a
* switch, at the player's team's. */
export function placeBases(writer: SetupWriter) {
placeSpawnPoints(writer, redBase, { team: red });
placeSpawnPoints(writer, blueBase, { team: blue });
}
/** Switching only between rounds: off as a round starts, on as it ends. */
export function startRound(authority: Authority) {
setTeamSwitching(authority, false);
}
export function endRound(authority: Authority) {
setTeamSwitching(authority, true);
}

The room’s scene calls placeBases as it mounts, as Where each team spawns says. The game’s own round system calls startRound as a round begins and endRound as it ends, as Systems shows a game’s system. Keep the time between rounds longer than cooldownSeconds, so a player who switches there can switch back. As a round ends, call balanceTeams first and turn switching on after it, so players switch from even teams.

defineTeam(key, options) returns a Team, a handle that every call names. Two handles are two teams even when their keys match, so always pass the handle your game declared. A call that names a team your game did not list throws in development, naming the call, and is refused with a logged reason in a published game. A team takes the following options:

Option Default What it does
name The key What a scoreboard and a nameplate show
color A colour from the key A CSS colour, which nameplates wear; a key such as "red" or "blue" takes that colour
maxPlayers No cap but the room’s The most players the team holds; balance and a switch respect it, setTeam does not
autoAssignable true Whether balance on join may put a player here
balanced true Whether the team counts when balance and a switch compare team sizes; a spectator team sets false
selectable true Whether a player may switch to it; an infection game’s zombies set false

When every team that balance may fill is full, a joining player gets no team, and the player is an ally of nobody until the game or the player’s switch gives the player one. A player on a spectator team is on a team, so characters() gives the player a character; a game keeps a spectator out of its objectives itself, such as by checking findTeam before a flag counts a touch.

The defaults and the setting that changes each

Section titled “The defaults and the setting that changes each”

Each row below is a default a player feels, and the setting that changes it:

Behaviour Default The setting
Teams None: every player is on one side teams({ teams: [red, blue] }), or teams({ freeForAll: true })
Team sizes No cap but the room’s defineTeam("hunter", { maxPlayers: 1 })
Balance on join The smallest autoAssignable team autoAssignable: false on each team, and the game’s own setTeam
Switching On, a 10-second cooldown, at most one player of difference switching: false, or switching: { cooldownSeconds, maxPlayerDifference }
Switching during play Follows switching setTeamSwitching(authority, false) as a round starts, true as it ends
A switch, or a balance, of a living player The character dies and respawns on the player’s new team’s points characters({ teamChange: TeamChangeEffect.Respawn }) moves the character there alive; Stay leaves it standing
A game’s setTeam on a living player The character stays where it stands The game moves the character itself
A player with no team No character until the player has a team characters({ spawnWithoutTeam: true })
The character’s saved place Not restored where points are placed for the player’s team characters({ restorePlace: true })
Friendly fire Off: a hit between allies applies nothing teams({ friendlyFire: true }), setFriendlyFire in play, or a weapon’s friendlyFire
Nameplates A plate wears its team’s colour teamColors: TeamColorMode.Off in the nameplate setting
Two teams on one side Two teams are allies only when they are one team isTeamAlly: (world, first, second) => ...

A player asks for a team with sendTeamSwitch(world, team) from the player’s page, as Counter-Strike’s jointeam asks. The room answers in the order the requests arrive. The promise settles with a result whose status is CommandStatus.Accepted, or CommandStatus.Refused with a TeamSwitchRefusal as its reason and the player’s team unchanged, so a picker shows a line for each reason. A picker greys its buttons while switching is off with isTeamSwitchingAllowed(world), or useIsTeamSwitchingAllowed() in a view.

A switch to the team the player is on is accepted and changes nothing, so a double click is not an error. Any other switch meets these refusals, in this order, each a member of TeamSwitchRefusal, such as TeamSwitchRefusal.SwitchingOff for switching-off:

  1. switching-off: switching is false, or the game called setTeamSwitching(authority, false).
  2. not-selectable: the team is declared selectable: false.
  3. team-full: the team holds its maxPlayers.
  4. unbalanced: the move would leave the largest and the smallest balanced team more than maxPlayerDifference apart, and does not even them. A move evens the teams when it goes to a balanced team at least two players smaller than the player’s. A move to a team that is not balanced, such as the spectators, is never refused unbalanced.
  5. too-soon: the player’s cooldown has not ended, or a switch already changed the player’s team this tick. Each change of team starts the cooldown but the first team on joining, so the player may join a friend at once. A move that evens the teams skips the cooldown.

The switch is not predicted: the player’s page shows the new team when the room’s answer arrives, one round trip later. Read the pending result with useLatestCommandResult(teams.commands.switch), and the seconds left of the player’s cooldown with useTeamCooldownSeconds(), so a picker can show “switch in 6 s”. A game whose rule differs, such as a switch only to a party’s team, replaces the answering system with a system of its own whose entry says replaces: teams.systems.takeSwitches, as Change an engine system says. That system reads teams.commands.switch and moves the player with setTeam(step, player, team, { cause: TeamChangeCause.Switched }).

By default, a switch accepted while the player’s character stands kills it, as What a change of team does to the player’s character says, so a switch is no free heal or escape from a fight.

A scene places team spawn points with <SpawnPoints team={red} points={[[-20, 0, 0], [-20, 0, 4]]} />. In code, pass the setup writer to placeSpawnPoints(writer, points, { team: red }), as placeBases does.

A call with a team replaces that team’s points alone. A player spawns at their team’s points, then at points for no team, then at <CharacterSpawn>. Within a list, the character takes the player’s seat’s point, or the next unoccupied point. With every point taken, it takes the nearest free place round the seat’s point, as Many players at one point says.

A point placed for a team the game did not list throws in development.

A respawn at the spawn, RespawnPlace.Spawn and the default, picks one of the player’s team’s points as the character stands, or one placed for no team where the player’s team has none, so a player who switched comes back on their new side. Where points are placed for the player’s team, the character’s saved place is not restored, since a place from another match could stand in the enemy’s half; characters({ restorePlace: true }) restores it for a persistent world with factions. The rest of the saved entity restores either way.

What a change of team does to the player’s character

Section titled “What a change of team does to the player’s character”

characters() reads the cause of TeamChangedEvent on the tick after the player’s team changes. The player’s own switch, or a move by balanceTeams, with the character standing, does what characters({ teamChange }) says:

  • TeamChangeEffect.Die, the default: the player’s character goes down with no killer, and DiedEvent carries DeathCause.TeamChange. Its respawn brings it back on the player’s new team’s points, as Counter-Strike and Team Fortress 2 kill a living switcher. A game that drops loot or counts lives on a death skips that cause.
  • TeamChangeEffect.Respawn: the character stands on the player’s new team’s points at once, alive and at full health, and each plugin’s onCharacterRespawn runs.
  • TeamChangeEffect.Stay: the character stays where it stands.

A character already down dies once: its respawn picks the player’s new side. A character with respawn={false} on its <CharacterSpawn> stays down until the game spawns it, as Counter-Strike’s switcher waits for the next round. A game’s own setTeam leaves the character where it stands, as an infection game’s bite turns a player in place. A system that replaces the switch’s answer passes { cause: TeamChangeCause.Switched } to setTeam, so teamChange applies to it too. The player’s first team at joining changes nothing: the character spawned on the team’s points already.

In a game with teams, a player with no team gets no character until the player has one, as Counter-Strike’s unassigned player has no body: a body with no team would fight everyone. isWaitingForTeam(world, player) reads true while the player waits, so a team picker shows its screen, and the player’s view target stays where the game put it, such as a spectator camera. As the player’s team arrives, by the player’s switch or the game’s setTeam, the character spawns on that team’s points. A player whose team becomes null keeps their character until it dies, and the character’s respawn waits for a team. characters({ spawnWithoutTeam: true }) spawns the character on the points placed for no team instead, as an ally of nobody. With characters({ autoSpawn: false }) the game spawns every character itself, and a free-for-all has no teams, so neither waits.

The writes take the room’s authority: a system’s step or the authority useAuthorityEffect hands a logic component:

  • setTeam(authority, entity, team) puts a player, an NPC or an object, such as a flag or a capture point, on a team, or on none with null, past every switching rule and maxPlayers, since it is the game’s own decision, and returns whether it applied. A join hook passes its own step, so a game’s picker can place a joining player itself. A living player’s character stays where it stands, as an infection game’s bitten player turns in place. An object on a team is that team’s ally: its shots pass through it.
  • setTeamSwitching(authority, isAllowed) turns players’ switching on or off for the room.
  • setFriendlyFire(authority, isEnabled) turns friendly fire on or off, for a warm-up or a hardcore round.
  • balanceTeams(authority) evens the balanced teams now: it moves the player who joined their team last, from the largest team to the smallest that has room, while the move evens the teams. It returns { moved, gap }, the players it moved and the gap left. The plugin never calls it on its own; call it between matches, as Counter-Strike balances at a match’s start.

A player who drops keeps their team for the room’s rejoin hold. One who comes back after it joins as a new player, and balance places the player again. The room’s checkpoint keeps every team, cooldown and setting.

The engine asks one question, and teams() answers it. The reads in the first rows below come from @spawnite/engine, so a system of your own reads teams the way damage and nameplates do:

Question In simulation code In a view
Which teams are in play readTeams(world) useTeams()
Which team is this entity on findTeam(world, entity) useTeam(entity)
Which team is this page’s player on findTeam(world, readLocalPlayer(world)) useTeam()
Are these two on one team isTeammate(world, a, b) useIsTeammate(a, b)
Are these two on one side isAlly(world, a, b) useIsAlly(a, b)
Who is on a team readTeamPlayers(world, red) useTeamPlayers(red)
Which team a key names findTeamByKey(world, key) none
How long until the player may switch readTeamCooldownSeconds(world, player) useTeamCooldownSeconds()
Whether players may switch now isTeamSwitchingAllowed(world) useIsTeamSwitchingAllowed()

readTeams, findTeam, findTeamByKey, isTeammate, isAlly, readInstigator and isFriendlyFireEnabled are the engine’s, and @spawnite/engine/teams exports findTeamByKey too; the rest, and every hook, are @spawnite/engine/teams’s. findTeamByKey finds a match’s teams as well as teams()’s.

An entity’s team comes from the player behind it: the player who controls it, else the one player whose presence it is, else its own team. A tank a red player drives fights for red, and goes back to its own team once the player lets go.

TeamChangedEvent lands on a player’s entity each time the player’s team changes, with from and to as team keys, null for none, since an event crosses the network as plain values, and a cause. findTeamByKey turns a key back into its handle. The cause is one of Joined, Switched, Set, Balanced or Match, the last as a match sets the player’s team. A change and its reversal within one tick are no change. To send an event to one team alone, name its players: emitEvent(step, TeamPingEvent, { at }, { to: readTeamPlayers(world, red) }).

A hit between allies applies nothing while friendly fire is off: no damage, no slow, no effect. dealDamage returns DamageRefusal.FriendlyFire for it and emits DamageRefusedEvent on the ally in place of DamagedEvent, as Health says. A weapon’s shot passes through an ally to what stands behind the ally, so it deals the ally no hit and emits nothing. A hit is judged by its instigator, the player and the team behind it as it was made, so a grenade that lands after its thrower switched teams is judged by the team the thrower threw it for. Self-damage is never spared, the player’s own rocket after the character’s respawn too.

Damage over time, such as a poison, deals a new hit each tick: pass the poisoner as source, and each tick is judged, and credited, by the poisoner’s team as it lands. So once the poisoner switches to the target’s team, the poison spares the new teammate, where a grenade, one hit made as it is thrown, does not. Each tick also follows the world’s friendly fire as it lands, unless the effect passes dealDamage its own friendlyFire on each tick.

A weapon’s friendlyFire overrides the world’s: true for a weapon that hurts teammates where friendly fire is off, false for one that never does. Left out, the weapon follows the world.

Abilities follow the same rule. Two players’ characters, and two entities that are each on a team, are set against each other, and the ally rule spares the caster’s teammates, so a team game marks nothing: abilities() makes each character a target as it spawns. The Abilities page has the whole rule.

Each hit’s record and each death’s carry the team the hit was judged for, instigatorTeam, as a team key, and the player behind it, instigatorPlayer, as Crediting a kill says. A score by team reads those, never the killer’s team at the death: a grenade that kills after its thrower switched scores for the team the thrower threw it for. The following score, for the two teams above, skips the killer’s own death and a teammate’s, and the engine’s tests run it in a real room:

packages/room/test/outside/teams/teamKills.ts
import {
createQuery,
DeathCause,
definePlugin,
defineTrait,
DiedEvent,
findEntity,
findTeam,
readEvents,
readInstigator,
setTrait,
spawn,
type AuthoritativeStep,
defineSystem,
Phase,
} from "@spawnite/engine/core";
import { blue, red } from "./twoTeams";
// Kills by team for the two teams of twoTeams.ts, built as a creator's
// plugin is, from the engine's public entries alone. The room adds one to
// the team each lethal hit was judged for, so a grenade that kills after
// its thrower switched scores for the team the thrower threw it for. The
// thrower's own death and a teammate's score nothing.
/** Each team's kills, on one scoreboard entity the room spawns at the
* first kill; the stream carries it to every page. */
export const TeamKillsTrait = defineTrait("outsideTeamKills", {
red: 0,
blue: 0,
});
const scoreboards = createQuery(TeamKillsTrait);
export const teamKills = definePlugin(() => ({
name: "team-kills",
// No runsOn: the room alone counts.
systems: [
defineSystem({
name: "count",
phase: Phase.Rules,
run: countTeamKills,
}),
],
}));
function countTeamKills(step: AuthoritativeStep) {
const world = step.world;
for (const { entity, record } of readEvents(step, DiedEvent)) {
const team = record.instigatorTeam;
if (!entity || record.cause !== DeathCause.Hit || team === null)
continue;
// The victim's own hit, such as a rocket at
// the victim's feet.
const victim = readInstigator(world, entity).player;
if (victim !== null && record.instigatorPlayer === victim) continue;
// A teammate's, where friendly fire is on. ponytail: the victim's
// team as the death is read, so a game's own setTeam between the
// hit and the reap moves it; a victim's team on the record
// would lift it.
if (findTeam(world, entity)?.key === team) continue;
const board =
findEntity(world, scoreboards) ??
spawn(step, { traits: [TeamKillsTrait] });
const kills = board.get(TeamKillsTrait) ?? { red: 0, blue: 0 };
if (team === red.key)
setTrait(step, board, TeamKillsTrait, { red: kills.red + 1 });
else if (team === blue.key)
setTrait(step, board, TeamKillsTrait, { blue: kills.blue + 1 });
}
}

A free-for-all lists teams({ freeForAll: true }): no teams, and every player fights every other:

packages/room/test/outside/teams/freeForAll.ts
import { characters } from "@spawnite/engine/characters";
import { teams } from "@spawnite/engine/teams";
// A free-for-all: no teams, and every player hurts every other.
export const plugins = [characters(), teams({ freeForAll: true })];

A co-op game needs no teams(): players are on one side, and a monster with no team fights them. A game that adds an NPC on the players’ side declares the one team and puts the NPC on it. A scene places one with <TeamMember team={defenders} /> inside its <Entity>, and a system calls setTeam:

packages/room/test/outside/teams/defenders.ts
import { characters } from "@spawnite/engine/characters";
import type { Authority, Entity } from "@spawnite/engine/core";
import { defineTeam, setTeam, teams } from "@spawnite/engine/teams";
// One team against NPCs: every player is a defender, a guard fights on
// their side, and a monster with no team fights them all.
export const defenders = defineTeam("defenders", { name: "Defenders" });
export const plugins = [
characters(),
teams({ teams: [defenders], switching: false }),
];
/** Puts a guard the game spawned on the players' side. */
export function enlistGuard(authority: Authority, guard: Entity) {
setTeam(authority, guard, defenders);
}

Players’ shots pass through the guard, and a chaser on the defenders’ team chases none of them.

  • A team’s secrets, such as a marker only red sees, wait for audiences after launch: every page reads every player’s team.
  • A team layout per level: a game declares every team it uses, and leaves out of balance the ones a level does not.
  • Neutral between two teams: two teams are allies or not.

A match scopes the team question: two players are teammates and allies only in one match. A queued match’s teams are its own and stay out of teams(), so court A’s sand is nobody’s teammate on court B, and teams() never balances a park player onto one. A match with no queue names teams teams() lists, which teams() balances and switches as this page says. A player’s match team reports TeamChangedEvent with the cause TeamChangeCause.Match. A match scores each team with addMatchScore, as the match page shows. The match answers before the team rule: a hit or a chase across matches is spared other-match whatever the teams say, and an eliminated member watches the member’s own side, as the match page’s scope says.

teams() is a readable plugin: the engine’s package ships its TypeScript source under node_modules/@spawnite/engine/readable/teams/. Each file reaches the engine through its public entries alone, so a kit could rebuild it, and every system that reads teams would follow the copy. The folder holds the following:

  • teams.ts: the plugin, its options and its answer to the team question.
  • declare.ts: defineTeam and a team’s settings.
  • membership.ts: each entity’s team, which only the plugin’s verbs write, and the room’s settings.
  • switching.ts: the switch command, its refusals, balance on join and balanceTeams.
  • reads.ts and hooks.ts: the reads, the hooks and sendTeamSwitch.
  • TeamMember.tsx: the scene’s component.
  • index.ts: the names @spawnite/engine/teams exports.