Skip to content

Player

import { Player } from "@sagl/server";

A connected player. You get Player objects from events and server.players; you don't create them. Getters read the latest state (synced from their game about 20 times a second); setters change it for them and everyone.

A Player stays valid until the playerQuit listeners have run; after that connected is false and changes are ignored.


Properties

Name Type Access Description
id number read Slot number, unique among connected players, reused after they leave.
name string read As given when joining, the name signing in gave them, or setName's.
token string \| null read What they started the game with (--token). See Signing in.
accountId string \| null read/write Who they are to you: server.auth's, or yours to set.
metadata Record<string, unknown> read/write What signing in told you about them (an avatar, a rank), and what you add.
data Record<string, unknown> read Your own per-player state.
connected boolean read False once they've left.
ip string read Their address (the forwarded one through a trusted proxy).
viaProxy boolean read They came through a trusted proxy.
connectHost, connectPort string, number read What they typed to connect.
ping number read Round-trip time, milliseconds.
alive boolean read Alive in the world.
paused boolean read Pause menu open.
focused boolean read False while alt-tabbed.
position Vector3 read Where they are (their vehicle's position while driving). Set it with setPosition().
heading number read Degrees, 0 north, anticlockwise.
velocity Vector3 read m/s, as their last sync (a passenger: their vehicle's).
keys number read The buttons they hold, Key bits: see playerKeys.
health number read/write Setting it and armour one after the other keeps both.
armour number read/write
skin number read/write Ped model; 0 is CJ.
money number read/write The server's count; their game shows exactly this.
wantedLevel number read/write 0-6 stars.
maxWantedLevel number read/write The most it can be, 0-6 (default 6).
world number read/write Virtual world.
color number read/write Their colour (0xRRGGBB, default white): their name in chat and their name tag, as SA-MP's SetPlayerColor.
nameTag NameTagSettings read/write Their name tag as everyone sees it: see Name tags.
score number read/write A number by their name in the player list (SetPlayerScore); the column shows once anyone's isn't 0.
weather number | null read/write Their own weather (0-22, -1 the game's cycle) over their world's (SetPlayerWeather); null: their world's.
worldBounds { minX, maxX, minY, maxY } | null read/write A box they can't leave (SetPlayerWorldBounds): their game pushes them back in, on foot or driving.
stuntBonus boolean read/write The game's stunt bonuses (wheelies, stoppies, two wheels, insane stunts): off, no message and no money. Default server.stuntBonus.
spectating Player | Vehicle | null read Who or what they watch: see spectate.
specialAction SpecialAction | null read/write Drinking, smoking, on the phone, hands up, dancing, a jetpack...: see Special actions.
interior number read/write The interior they're in: the game's areas, 0 outside, 1-18 its interiors (as SA-MP's SetPlayerInterior). Their game shows it, and they see players and vehicles in the same one. Teleports keep it: set both to go in or out. See Interiors.
camera PlayerCamera read Their camera: see Camera.
vehicle Vehicle | null read The vehicle they're in.
seat number | null read 0 driver, 1-8 passenger, null on foot.
lastVehicle Vehicle | null read The vehicle they last drove (kept from ambient cleanup).
remoteVehicle Vehicle | null read The vehicle they remote-control.
weapon number read/write The Weapon in their hand (set to one they have; 0 unarmed).
weapons { slot, weapon, ammo }[] read What they carry.
infiniteSprint boolean read/write Never tires.
skinAnimations boolean read/write Walks and runs like their skin (true) or CJ.
radioNameHidden boolean read/write Hides radio station names on their screen.
map GameMap read Their own pause menu map.
draw ScreenDraw read Drawing on their screen: text, boxes, images.
hud PlayerHud read Their mission HUD: blips, objective text, timers, result screens.
ui PlayerUi read UI documents the server opens on their screen: shops, dialogs, forms.
server.on("playerSpawn", (player) => {
  player.health = 100;
  player.armour = 50;
  player.skin = player.data.team === "cops" ? 280 : 0;
  player.wantedLevel = 0;
  player.infiniteSprint = true;
});

Methods

setPosition(position, heading?)

setPosition(position: Vector3, heading?: number): void

Teleports the player (and their vehicle, if they're driving), outside: if the game had taken them into an interior (walking onto a door marker), they're out of it.

Parameter Type Description
position Vector3 Where, in world coordinates.
heading number Degrees. Default 0.
player.setPosition({ x: 1481.2, y: -1771.6, z: 18.8 }, 0); // City Hall

send(text, color?, options?)

send(text: string, color?: number, options?: { markdown?: boolean }): void

Shows a message to this player only.

Parameter Type Description
text string The message. {RRGGBB} colours what follows; {key:ID} shows an action's key.
color number Optional 0xRRGGBB.
options.markdown boolean The text is markdown (bold, italic, code, links) instead of {RRGGBB} colours.
player.send("You can't do that here.", Color.Red);

fadeOut(ms?, color?), fadeIn(ms?)

fadeOut(ms?: number, color?: MapColor): Promise<void>
fadeIn(ms?: number): Promise<void>

Fades their screen out to color (default black) over ms (default 500), and keeps it there until fadeIn(). Each resolves when the fade is done. The HUD fades with it, as in the game.

await player.fadeOut();
player.setPosition(safehouse);
await player.fadeIn();

playAnim(block, name, options?)

playAnim(block: string, name: string, options?: { loop?: boolean; ms?: number; hold?: boolean; upperBody?: boolean }): Promise<void>

Plays one of the game's animations on them, or one of your own, seen by everyone: e.g. ("PED", "phone_talk"), ("VENDING", "VEND_Drink2_P"), ("PAYPHONE", "pickup"). ms stops it after that long; without, it plays to its end (looping: until stopAnim(), or they move). Blocks other than PED stream in first. An animation their game doesn't have is skipped (and logged there). Resolves after ms (or at once).

hold keeps it on its last frame until the next one replaces it (SA-MP's ApplyAnimation freeze), and the next waits for it to finish: animations played one after another join up, however the messages were timed (the first may start late while its block streams in). Use it for each animation of a chain, and stopAnim() after the last:

await player.playAnim("VENDING", "VEND_Use", { ms: 2600, hold: true });
await player.playAnim("VENDING", "VEND_Use_pt2", { ms: 400, hold: true });
await player.playAnim("VENDING", "VEND_Drink2_P", { ms: 3330, hold: true });
player.stopAnim();

upperBody plays it on the upper body only (the game's secondary task), so they can walk meanwhile: animations made for it end in _P or _prtl, e.g. ("GANGS", "smkcig_prtl", { upperBody: true }).

Throws RangeError for malformed names.

stopAnim()

Stops whatever animation they're playing.

isNear(position, radius, maxDz?)

isNear(position: Vector3, radius: number, maxDz?: number): boolean

Whether they're within radius m of position on the ground, and no more than maxDz (default 3) above or below it: the check to make before trusting a client script that says its player is at something.

dialog(options)

dialog(options: { style?, title?, body?, button1?, button2?, markdown? }): Promise<{ response: boolean; listItem: number; input: string }>

A dialog, as SA-MP's ShowPlayerDialog, resolving with their answer.

style
"msgbox" (default) Text and buttons.
"input", "password" A line to type in (hidden for a password).
"list" One row a line of body, to choose from.
"tablist" Rows of columns (separated by \t).
"tablistHeaders" The same, the first row the headings.

{RRGGBB} colours a part of the text, and {key:ID} shows an action's key. With markdown: true the body of a msgbox, input or password dialog is markdown instead. response is true for the first button (Enter, or a double click on a row), false for the second (Escape); listItem the row chosen (-1 if not a list); input what they typed. One at a time: a new one (or hideDialog()) answers the one showing with response: false. Client scripts have the same, sagl.dialog().

const login = await player.dialog({ style: "password", title: "Login", body: "Your password:", button1: "Login", button2: "Quit" });
if (!login.response) return player.kick();
const shop = await player.dialog({ style: "tablistHeaders", title: "Ammu-Nation", body: "Weapon\tPrice\nPistol\t$500\nShotgun\t$1200", button1: "Buy", button2: "Close" });
if (shop.response && shop.listItem === 0) { ... }

screenEffects

readonly screenEffects: ScreenEffects

Screen effects (built in, or your shaders) on their screen.

player.screenEffects.add("nightvision", { fadeMs: 300 });
menu(options: MenuOptions): PlayerMenu
readonly currentMenu: PlayerMenu | null

A menu like the game's shops have (SA-MP's CreateMenu and ShowMenuForPlayer): a box at the top left with a title and rows, one of them chosen.

Option Type Description
title string In the game's heading font.
image string An image over the menu, such as a logo, edge to edge (the title then shows as a subheading under it; leave the title out for the logo alone): a client file, or one of the game's own textures from the player's copy, "game:<txd>/<texture>" (e.g. "game:garag3_lawn/ws_Transfender_dirty").
rows MenuRow[] Each a text; or [text, value] with a right-hand column (a price, "Fitted"); or { text, value?, swatch? } with a colour swatch (0xRRGGBB). Game codes (~r~) and gxt() work.
row number The row chosen to begin with. Default 0.
footer MenuRow A line under the box, such as their cash: a text, or a row's form ([text, value], { text, value?, swatch? }). A grid's shares the line under it with the chosen cell's value.
hints MenuHint[] The buttons' hints along the bottom left, the first leftmost: { key, label }, key being "select", "back", "updown" or "arrows" (the keys, or a controller's buttons, for it) or a key icon's name ("space", "f"). Default: Select and Back; [] for none.
columns number Above 1: a grid this many across, like the game's colour picker. Each row is a cell (its swatch, else its text), the arrow keys move every way, and the chosen cell's text and value show under the grid.
onChoose (row, menu) => void They moved to a row with Up or Down. Show it off: a part on a car, a colour.
onSelect (row, menu) => void They pressed Enter (or Space) on a row.
onBack (menu) => void They pressed Backspace, Escape or F (as in the game). The menu stays up: close it, or show the one before.

The menu takes their keys while it's up, so they can't walk or drive. Only one shows at a time: opening another replaces it. currentMenu is the one showing.

PlayerMenu has:

  • row: the row chosen;
  • isOpen;
  • update({ title?, rows?, row?, footer?, hints? }): changes it in place;
  • close().

Client scripts have the same, sagl.menu().

const guns = [["Pistol", 500], ["Shotgun", 1200]] as const;
player.menu({
  title: "Ammu-Nation",
  rows: guns.map(([name, price]) => [name, `$${price}`]),
  footer: `Cash: $${player.money}`,
  onSelect: (row, menu) => {
    const [name, price] = guns[row];
    if (player.money < price) return player.hud.notice("~r~Not enough cash.");
    player.giveMoney(-price);
    menu.update({ footer: `Cash: $${player.money}` });
  },
  onBack: (menu) => menu.close(),
});

setCheckpoint(position, size?), disableCheckpoint()

Their checkpoint, as SA-MP's SetPlayerCheckpoint: a red cylinder on the ground, size m across (default 2), with a radar blip. One at a time. Coming into it and leaving it fire playerEnterCheckpoint and playerLeaveCheckpoint; inCheckpoint says whether they're in it.

setRaceCheckpoint(position, { next?, size?, type? }), disableRaceCheckpoint()

Their race checkpoint, as SA-MP's SetPlayerRaceCheckpoint: the game's own, its arrow pointing at next. type: 0 normal, 1 finish, 2 nothing (no arrow), 3 in the air (a ring), 4 the air finish. Size default 4. Fires playerEnterRaceCheckpoint / playerLeaveRaceCheckpoint.

const route = [a, b, c];
let i = 0;
player.setRaceCheckpoint(route[0], { next: route[1] });
server.on("playerEnterRaceCheckpoint", (p) => {
  if (++i >= route.length) return p.disableRaceCheckpoint();
  p.setRaceCheckpoint(route[i], { next: route[i + 1] ?? route[i], type: i === route.length - 1 ? 1 : 0 });
});

attachObject(slot, model, bone, { offset?, rotation?, scale? })

An object they hold, as SA-MP's SetPlayerAttachedObject: in slot (0-9, setting it again replaces it), on a Bone (SA-MP's 1-18: Head, RightHand, Spine...), offset (m), turned (degrees) and scaled from it. Everyone sees it, following every animation. removeAttachedObject(slot), isAttachmentSlotUsed(slot). Client scripts can attach objects to their own player too (sagl.player.attachObject), which playerAttachObject can refuse.

player.attachObject(0, 1210, Bone.RightHand, { offset: { x: 0.1, y: 0.02, z: 0 } }); // a briefcase

chatBubble(text, { color?, distance?, ms? })

Text over their head for a while, as SA-MP's SetPlayerChatBubble: seen within distance m (default 20), for ms (default 5000). A leading {RRGGBB} is its colour. Another replaces it.

setName(name)

setName(name: string): boolean

Gives them another name (SA-MP's SetPlayerName): 3-24 letters, digits and _[]().$@=, and no one else's (in any case). Everyone's game shows it: name tags, the player list, chat. Returns false if it can't be theirs.

spectate(target)

spectate(target: Player | Vehicle | null): void

Watches another player or a vehicle (SA-MP's TogglePlayerSpectating with PlayerSpectatePlayer and PlayerSpectateVehicle): no one sees them meanwhile, and their camera follows the target (a player's vehicle while they're in one), keeping up wherever it goes. Another target switches to it; null ends it and puts them back where they were. Their keys still reach playerKeys, for "next player" controls.

admin.spectate(suspect);
// later
admin.spectate(null);

holster()

Puts the weapon in their hand away. Returns a function that gives it back (if they still have it). Cinematics do it for you.

isAimingAt(target, options?)

isAimingAt(target: { position: Vector3 } | Vector3, options?: { range?: number; angle?: number }): boolean

Whether they're aiming a firearm at a ped, player, vehicle or spot: holding aim, within range m (default 10), their camera within angle degrees of it (default 12). For a ped that gives up at gunpoint.

setVisibleFor(viewer, visible)

Whether viewer sees them at all (default visible). For scenes each player plays alone in the same spot: each sees only themselves answer a phone.

playCrimeReport(suspect, crime)

playCrimeReport(suspect: Player | Vector3, crime: number): void

Plays them the police scanner reporting a crime (SA-MP's PlayCrimeReportForPlayer): crime is one of the game's (Crime), suspect a player or a spot, whose area the scanner names.

putInVehicle(vehicle, seat?)

Puts them straight into a seat (0 the driver's, the default; 1-8 passengers), as SA-MP's PutPlayerInVehicle. The vehicle must be near enough for their game to have it.

fightingStyle, drunkLevel

fightingStyle (read/write): a FightingStyle (Normal, Boxing, KungFu, KneeHead, GrabKick, Elbow), as SA-MP's numbers; everyone sees them fight so. drunkLevel (read/write): as SA-MP's, above 2000 their camera sways, falling by 60 a second (reading it gives what it's down to).

respawn()

respawn(): Promise<void>

Spawns them again without killing them (SA-MP's SpawnPlayer): the screen fades, they're taken out of any vehicle, their animation, special action and camera are reset, they're unfrozen, health goes to 100 and armour to 0, and playerSpawn fires, so your spawn handler places and equips them as on any spawn. Resolves once the screen has faded back in. Does nothing while they're dead (they respawn by themselves).

slideTo(position, heading?, ms?)

slideTo(position: Vector3, heading?: number, ms?: number): Promise<void>

Moves them on foot to a spot nearby and turns them to heading (degrees; default their own), with the game's own slide, as its machine scripts put a player in front of a vending machine. Unlike setPosition, it isn't a teleport: no drop from the game standing them on z. Once close (or after 2.5 s) they're set exactly on the spot and heading, at the height they stand at, so an animation after starts from the same place every time. Resolves once they're there and turned, or after ms (default 2000). Works while they're frozen.

player.frozen = true;
await player.slideTo({ x: 2326.2, y: -1646.1, z: 14.2 }, 0);
await player.playAnim("VENDING", "VEND_Use", { ms: 2600 });

Interiors

player.interior = 3;
player.setPosition({ x: 384.8, y: 173.8, z: 1008.4 });   // City Hall
// and out again
player.interior = 0;
player.setPosition({ x: 1481, y: -1772, z: 18.8 });

The game's interiors are real places far off the map (high up, mostly), shown only while a player's game is "in" them. With the server option gameEntrances on (the default), the game's own yellow door markers take players in and out by themselves, and the server hears it (playerInterior); off, only the server does.

Objects, pickups and labels take an interior option (Objects, pickups and labels), vehicles vehicle.interior.

Name tags

player.nameTag = { hidden?: boolean; text?: string | null; color?: number | null };
player.setNameTagFor(viewer: Player, tag: NameTagSettings | null): void

The name over their head, as everyone sees it: hidden takes it away, text shows instead of their name (a mask's "Stranger 4821"), color (0xRRGGBB) instead of player.color. Setting nameTag replaces it ({}: as normal). setNameTagFor changes it for one viewer only, over nameTag (as SA-MP's ShowPlayerNameTagForPlayer); null puts it back as everyone sees it. Hidden, their "paused" and "tabbed out" go too.

How every tag shows (the distance, line of sight, ids, health bars) is the server's: server.nameTags.

// /mask: a stranger to everyone but staff.
player.nameTag = { text: `Stranger ${1000 + player.id}` };
for (const staff of admins) player.setNameTagFor(staff, { text: `${player.name} (masked)` });

Special actions

player.specialAction: SpecialAction | null

As SA-MP's SetPlayerSpecialAction. Everyone sees it, players arriving later too, until it's set to null (or they die; getting in a vehicle ends all but the phone).

Action What
"drinkBeer", "drinkWine", "drinkSprunk" A bottle or can in hand. Fire drinks (beer +250 and wine +500 to drunkLevel); enter/exit drops it. Fire doesn't punch meanwhile.
"smoke" A cigarette in hand. Fire takes a drag; enter/exit drops it.
"phone" On the phone; they can walk.
"carry" Arms out, carrying something; they can walk.
"handsUp", "dance1"-"dance4", "piss" A pose they keep, in place.
"jetpack" A jetpack. Null takes it away.
server.commands.register(command("handsup").executes(({ player }) => { player.specialAction = "handsUp"; }));
server.on("playerKeys", (player, keys, old) => {
  if (player.specialAction === "handsUp" && keyPressed(keys, old, Key.Sprint)) player.specialAction = null;
});

The prop takes attachment slot 10 (past attachObject's 0-9).

Camera

readonly camera: PlayerCamera

Full control of their camera: shots, glides, sequences, paths through points, a freecam they fly, field of view and roll. See Camera.

await player.camera.set({ position: { x: 1500, y: -1700, z: 80 }, lookAt: { x: 1480, y: -1750, z: 13 } });
await player.camera.set({ position: { x: 1420, y: -1700, z: 60 }, lookAt: { x: 1480, y: -1750, z: 13 }, fov: 50, ms: 8000 });
player.camera.reset();

Splash screen

player.splash.show(options?: { text?: string; fadeMs?: number }): void
player.splash.hide(options?: { fadeMs?: number }): void
player.splash.visible: boolean

Their loading screen (your branding: background, logo, name), kept up or shown again while you set the scene behind it. Their game's sound is muted while it shows; as it fades out (fadeMs, default 1000), the sound fades back in. text is a line under the name ("Loading your character..."). show() fades in over fadeMs (default 300).

hide() waits for the world around their camera to load first (at most a few seconds), so it never lifts off a half-drawn scene: move them, set the camera, and hide it at once.

With the server option splash, it stays up from joining (the download screen turning into it, the same screen) until you hide it:

const server = new Server({ splash: true });

server.on("playerSpawn", (player) => {
  // The login screen, set up unseen.
  player.world = 1000 + player.id;
  player.setPosition({ x: 1880, y: -1194.8, z: 30 });
  player.hud.set({ visible: false });
  player.camera.set({ position: { x: 1890.1, y: -1194.8, z: 25.8 }, lookAt: { x: 1933.4, y: -1196.2, z: 18.8 } });
  player.splash.hide();
});

// Later: covering a move across the map.
player.splash.show({ text: "Taking you home..." });
setTimeout(() => {
  player.setPosition(home);
  player.splash.hide();
}, 350);  // once it's faded in

Client scripts have the same: sagl.splash.

frozen

boolean, read/write: while true they can't move (their controls are off, as in a cutscene); animations still play.

player.frozen = true;
await player.playAnim("PED", "phone_in", { ms: 1200 });

say(line)

say(line: { dialogue: string; table?: string; subtitle?: string; ms?: number; to?: Player[]; effects?: AudioEffects }): Promise<void>

Says a line of the game's mission dialogue as CJ: its recording, from this player, with its text as the subtitle. Heard by to, or everyone within 40 m. Resolves when it's done. effects puts it through audio effects (then the lips don't move).

await player.say({ dialogue: "RYD2_CA", table: "RYDER2" });   // "Hey, Ryder, where we going?"

subtitle(text, ms?)

subtitle(text: string, ms?: number): void

A subtitle at the bottom of their screen, in the game's style, for ms (default: about as long as reading it takes). Shown only if they have Subtitles on in their pause menu.

player.subtitle("Get in the car.");

kick(reason?)

kick(reason?: string): void

Disconnects the player and tells them why. Their game shows a "Kicked" screen with your server's name and the reason. It doesn't reconnect by itself: the player presses Enter to try again, or Esc to quit.

Parameter Type Description
reason string Shown to them (up to 128 characters).

Other cases are shown too. When the server shuts down, players see "Server closed" and their games keep trying to reconnect. If the connection drops, they see "Connection lost" and their games reconnect by themselves. A "Connection problem" notice appears after 3 seconds without hearing from the server.

if (player.ping > 500) player.kick("Ping too high");

giveMoney(amount)

giveMoney(amount: number): void

Adds money, or takes it if amount is negative.

Parameter Type Description
amount number How much.
player.giveMoney(-200); // pay for a pistol

giveWeapon(weapon, ammo)

giveWeapon(weapon: number, ammo: number): void

Gives a weapon into its slot (replacing what was there), or adds ammo if they have it.

Parameter Type Description
weapon number Weapon.
ammo number Rounds.
player.giveWeapon(Weapon.M4, 300);
player.weapon = Weapon.M4;

setAmmo(weapon, ammo)

setAmmo(weapon: number, ammo: number): void

Sets the ammo of a weapon they have.

Parameter Type Description
weapon number Weapon.
ammo number Rounds.
player.setAmmo(Weapon.Sniper, 5);

removeWeapon(weapon), resetWeapons()

removeWeapon(weapon: number): void
resetWeapons(): void

Takes one weapon, or all of them.

server.on("zoneEnter", (player, zone) => { if (zone === safeZone) player.resetWeapons(); });

setStat(stat, value)

setStat(stat: number, value: number): void

Sets a game stat. Only the server changes stats: playing doesn't.

Parameter Type Description
stat number Stat, e.g. Stat.Stamina, Stat.PistolSkill.
value number Most go 0-1000.
player.setStat(Stat.PistolSkill, 1000); // dual pistols
player.setStat(Stat.MaxHealth, 1000);   // 176 health

getStat(stat), resetStat(stat)

getStat(stat: number): number | undefined
resetStat(stat: number): void

A stat as the server set it (undefined: a new game's value), and setting it back to a new game's value.

if ((player.getStat(Stat.DrivingSkill) ?? 0) < 500) player.send("Take some driving lessons!");

clearWantedLevel({ parole? })

clearWantedLevel(options?: { parole?: boolean }): void

Clears their wanted level. With parole, as the game's Pay 'n' Spray: their old stars flash for 20 seconds, and a crime meanwhile brings them all back (where the population's wanted is on; playerWantedLevel hears it).

player.clearWantedLevel({ parole: true });

removeFromVehicle()

removeFromVehicle(): void

Puts them out of their vehicle, beside it.

if (player.vehicle?.data.locked) player.removeFromVehicle();

remoteControl(vehicle, options?)

remoteControl(vehicle: Vehicle | null, options?: { detonate?: boolean }): boolean

They drive vehicle from where they stand, as with an RC car, until they press enter/exit, it blows up, or this is called with null. Works with any vehicle.

Parameter Type Description
vehicle Vehicle | null Empty, in their world. null ends it.
options.detonate boolean Fire blows it up (and an RC Bandit blows up touching a car).

Returns false if it can't be given (they're in a vehicle, it's taken, another world, a wreck).

const rc = server.createVehicle(441, player.position); // RC Bandit
player.remoteControl(rc, { detonate: true });

emit(channel, data?)

emit(channel: string, data?: unknown): void

Sends data to this player's client scripts, where sagl.on(channel, fn) gets it. The same as server.channel(channel).send(player, data).

Parameter Type Description
channel string The channel.
data unknown Anything JSON can hold, up to 256 KB.
player.emit("notify", { text: "Mission passed!", colour: "#dc9a32" });