Skip to content
Docs

The jugadores service

Reference for the jugadores service. Who is in the room, humans and bots: their position, abilities, actions, view and state.

DescribesFormato 1, API 1 For those who write code This page is generated from the SDK sources.

On this page

Who is in the room, humans and bots: their position, abilities, actions, view and state.

The types used in the signatures (Vec3, Texto, the selector) are in the API reference.

Functions and properties of jugadores#

jugadores.todos#

ts
jugadores.todos(): Jugador[]

Players present, humans and bots.

From docs/EJEMPLOS.md, «interfaz: menú»:

ts
for (const j of jugadores.todos()) j.congelado = true;       // un menú no pausa la partida

jugadores.humanos#

ts
jugadores.humanos(): Jugador[]

Players present that are not bots.

From games/copa-de-bloques/scripts/principal.ts:

ts
hum = jugadores.humanos()[0] ?? jugadores.todos()[0];

jugadores.porId#

ts
jugadores.porId(id: string): Jugador | null

The player with that id, or null if there is none.

jugadores.alEntrar#

ts
jugadores.alEntrar(fn: (j: Jugador) => void): void

A player enters the room. It is also called for those already in when the event is registered.

From docs/EJEMPLOS.md, «interfaz: HUD, mensajes y cronómetro»:

ts
jugadores.alEntrar((j) => {
  interfaz.hud('puntos', { icono: 'estrella', texto: interfaz.t('puntos', { n: 0 }), lugar: 'arriba-izquierda' }, j);
});

jugadores.alSalir#

ts
jugadores.alSalir(fn: (j: Jugador) => void): void

A player leaves the room.

From games/isla-taller/scripts/principal.ts:

ts
jugadores.alSalir((j) => {
  for (const p of pilas.get(j.id) ?? []) p.eliminar();
  pilas.delete(j.id);
});

jugadores.alAccion#

ts
jugadores.alAccion(accion: 'saltar' | 'accion' | 'accion2', fn: (j: Jugador) => void): void

A player presses an action (once per press).

From docs/EJEMPLOS.md, «jugadores: estado por jugador, acciones y caídas»:

ts
jugadores.alAccion('accion', (j) => {            // una vez por pulsación
  j.impulsar([0, 14, 0]);
  sonido.tocar('poder', { para: j });
});

jugadores.alCaer#

ts
jugadores.alCaer(fn: (j: Jugador) => void): void

A player fell below alturaCaida. The room has already respawned them; here you take a life, add a penalty, and so on.

From docs/EJEMPLOS.md, «jugadores: estado por jugador, acciones y caídas»:

ts
jugadores.alCaer((j) => {                        // la sala ya lo devolvió a su aparición
  const vidas = (j.datos.vidas as number) - 1;
  j.datos.vidas = vidas;
  interfaz.hud('vidas', { icono: 'corazon', texto: interfaz.t('vidas', { n: vidas }), estilo: vidas === 1 ? 'peligro' : 'normal' }, j);
  if (vidas <= 0) juego.terminar({ resultado: 'derrota', puntaje: j.puntos, de: j });
});

jugadores.alCambiarPantalla#

ts
jugadores.alCambiarPantalla(fn: (j: Jugador) => void): void

A player's screen changed size or orientation. It is also called once when the screen is first known.

From docs/EJEMPLOS.md, «interfaz: mensajes que no estorban, menú con opción deshabilitada, textos anidados»:

ts
// Textos mas cortos en telefonos verticales.
jugadores.alCambiarPantalla((j) => interfaz.hud('ayuda', { texto: interfaz.t(j.pantalla.vertical ? 'ayudaCorta' : 'ayuda'), lugar: 'abajo-centro' }, j));

jugadores.alCambiarRanura#

ts
jugadores.alCambiarRanura(fn: (j: Jugador, ranura: number) => void): void

The player picked another slot of the hotbar.

From games/valle-abierto/scripts/principal.ts:

ts
jugadores.alCambiarRanura((j) => sonido.tocar('tic', { para: j, volumen: 0.4 }));

Jugador#

A player in the room: a person or a bot.

PropertyTypeDescription
jugador.idstringRead-only. Stable during the match: 'j1', 'j2'...
jugador.nombrestringRead-only. Name of the player.
jugador.esBotbooleanRead-only. true if a bot drives it.
jugador.indicenumberRead-only. 0 for the first one in.
jugador.presentebooleanRead-only. false once the player has left the room.
jugador.posicionVec3Position of the feet. Assigning it teleports the player.
jugador.velocidadVec3The actual velocity: walking plus pushes.
jugador.direccionnumberRead-only. Where it faces, in degrees (0 is +Z).
jugador.enSuelobooleanRead-only. true while standing on something.
jugador.sueloPieza | nullRead-only. The piece it is standing on, if any.
jugador.rapideznumberUnits per second. Defaults to 8.
jugador.saltonumberJump height in units. Defaults to 2.6. 0 disables jumping.
jugador.saltosExtranumberExtra jumps in mid-air. Defaults to 0.
jugador.congeladobooleantrue: it does not respond to the controls (it still falls and platforms still carry it).
jugador.aparicionstringId of the spawn point it returns to with reaparecer or after falling out of the world.
jugador.puntosnumberThe player's points counter; interfaz.marcadorDePuntos shows it. Defaults to 0.
jugador.datosRecord<string, unknown>Free data for the script, per player.
jugador.entrada{ x: number; z: number }Read-only. Where the player wants to move right now, on the world plane: x and z between -1 and 1 (0, 0 when nothing is pressed).
jugador.pantalla{ ancho: number; alto: number; tactil: boolean; vertical: boolean }Read-only. This player's screen: useful to shorten texts on phones. In greengames probar and for bots it is 1280 x 720, not touch. It changes if the player rotates the phone (see jugadores.alCambiarPantalla).
jugador.apariencia{ torso?, piernas?, piel?, gorro? } | nullColors of this player's avatar. Assigning an object changes them; null goes back to the ones for its player number.
jugador.equipostringTeam name, free text.
jugador.vistaTipoVistaRead-only. The type of view this player has right now.
jugador.mirada{ origen: Vec3; direccion: Vec3 }Read-only. Where the player looks from and toward: the eyes and the direction of the gaze. In first person it follows the mouse.
jugador.ranuranumberSelected slot of the hotbar (0 is the first). The player changes it with the wheel, keys 1 to 9 or by touching it; the script can set it too.
jugador.puntero{ origen: Vec3; direccion: Vec3 }Read-only. Pointer ray: from the camera, through the center of the screen (the crosshair). In first person it equals mirada. For bots and in greengames probar it is the look direction.
jugador.vuelobooleantrue: it flies. Gravity does not affect it; it goes up with saltar and down with accion2.
jugador.enAguabooleanRead-only. It is inside a liquid block of the terrain (it floats, and swims with saltar).

jugador.teletransportar#

ts
jugador.teletransportar(destino: Vec3 | string, rotacionY?: number): void

Takes the player to a point or to a spawn point (by id), and zeroes its velocity.

From docs/EJEMPLOS.md, «jugadores: mover, teletransportar y cambiar habilidades»:

ts
mundo.alTocar('#portal', (_p, j) => j.teletransportar('sala-2'));       // id de una aparición

jugador.reaparecer#

ts
jugador.reaparecer(): void

Sends the player back to its current spawn point.

From docs/EJEMPLOS.md, «actores: personajes del script»:

ts
actores.alTocar('#enemigo', (enemigo, j) => { j.reaparecer(); enemigo.posicion = [10, 0, 10]; });

jugador.impulsar#

ts
jugador.impulsar(velocidad: Vec3): void

Adds velocity instantly (bounces, trampolines).

From docs/EJEMPLOS.md, «jugadores: mover, teletransportar y cambiar habilidades»:

ts
mundo.alTocar('#trampolin', (_p, j) => j.impulsar([0, 20, 0]));

jugador.pulsa#

ts
jugador.pulsa(accion: AccionEntrada): boolean

true while the action is held down.

From docs/CONTRATO.md, section 4.3:

ts
jugador.pulsa('primaria')

jugador.apunta#

ts
jugador.apunta(distancia?: number): Impacto | null

The first thing in front of the player, up to distancia (4 by default): the piece being looked at. For "interact with what I am looking at".

jugador.caminarA#

ts
jugador.caminarA(destino: Vec3 | null): void

Sends the avatar walking to a point (it goes around obstacles). null stops it. Any movement by the player cancels it.

jugador.apuntaBloque#

ts
jugador.apuntaBloque(distancia?: number): BloqueApuntado | null

The terrain block the player is pointing at, up to distancia units from the eyes (5 by default), or null. It carries the face touched and the neighboring cell where a new block would go.

From games/valle-abierto/scripts/principal.ts:

ts
const a = j.apuntaBloque(ALCANCE);

Behavior notes#

Pointer and hotbar (version 1.1). Two more actions, declared in controles.acciones like the others:

ActionKeyboard and mouseGamepadTouch screen
primariaLeft click, or JRight triggerHolding a finger still on the game
secundariaRight click, or KLeft triggerA short tap on the game

They are used like the others: jugadores.alAccion('primaria', fn) (once per press) and jugador.pulsa('primaria') (while held). When a game declares either of them:

  • the mouse is captured on click in third person too (Esc releases it; the click that captures it does not count as an action) and the crosshair appears in the center. If the browser does not allow capturing it, you look around by dragging and clicks act the same;
  • jugador.puntero is the ray from the camera through the crosshair. In first person it is the same as jugador.mirada; in third person it starts at the camera, behind the avatar. For bots it is the look direction;
  • the hotbar is drawn with interfaz.barraRapida and a slot is picked with the mouse wheel, keys 1 to 9, the gamepad d-pad (left and right) or by touching a slot. The selected one is jugador.ranura.

They work for any game (shooting, picking up, using what you look at), not only for cube games.

Details worth knowing:

  • rapidez accepts 0 to 40 and salto 0 to 30; values out of range are clamped.
  • velocidad returns the actual velocity (walking plus pushes). To know what the player wants to do, use entrada.
  • A horizontal impulsar slows down on its own (friction of 0.82 per frame on the ground, 0.985 in the air): it is a push, not a sustained speed.
  • teletransportar puts the player on the ground right away if there is floor under its feet.
  • pantalla is 1280 x 720, not touch, for bots and in greengames probar. On phones, a HUD chip comfortably shows about 24 characters per line (it wraps up to three lines).

Complete examples#

Complete scripts from docs/EJEMPLOS.md. Each one assumes a scene containing what it names, and the text keys (interfaz.t('...')) must exist in textos of juego.json.

jugadores: per-player state, actions and falls#

scripts/principal.ts
import { interfaz, juego, jugadores, sonido } from '@greengames/sdk';

juego.alIniciar(() => {
  jugadores.alEntrar((j) => {
    j.datos = { vidas: 3 };
    interfaz.hud('vidas', { icono: 'corazon', texto: interfaz.t('vidas', { n: 3 }) }, j);
  });

  jugadores.alCaer((j) => {                        // la sala ya lo devolvió a su aparición
    const vidas = (j.datos.vidas as number) - 1;
    j.datos.vidas = vidas;
    interfaz.hud('vidas', { icono: 'corazon', texto: interfaz.t('vidas', { n: vidas }), estilo: vidas === 1 ? 'peligro' : 'normal' }, j);
    if (vidas <= 0) juego.terminar({ resultado: 'derrota', puntaje: j.puntos, de: j });
  });

  jugadores.alAccion('accion', (j) => {            // una vez por pulsación
    j.impulsar([0, 14, 0]);
    sonido.tocar('poder', { para: j });
  });
});

jugadores: moving, teleporting and changing abilities#

scripts/principal.ts
import { juego, mundo } from '@greengames/sdk';

juego.alIniciar(() => {
  mundo.alTocar('#trampolin', (_p, j) => j.impulsar([0, 20, 0]));
  mundo.alTocar('#portal', (_p, j) => j.teletransportar('sala-2'));       // id de una aparición
  mundo.alTocar('#botas', (botas, j) => { botas.eliminar(); j.saltosExtra = 1; j.rapidez = 11; });
  mundo.alTocar('#hielo', (_p, j) => { j.congelado = true; });
});

Next#