
Disparos en tercera persona
Disparas viendo a tu personaje desde atrás o sobre el hombro, lo que te deja ver lo que lo rodea y suele sumar coberturas, saltos y movimientos acrobáticos.
También se llama: TPS, shooter en tercera persona
Esta es una ficha básica: tiene la definición y la clasificación. Las fichas completas suman historia, juegos y una demo.
Demo propia
Controles. Flechas o WASD para moverte (respecto de la cámara), ratón para apuntar (haz clic en el juego para capturarlo) y clic izquierdo o espacio para disparar. Mantén Mayús, C o clic derecho para agacharte tras un muro. En móvil, los botones en pantalla y arrastrar con el dedo para girar la cámara.
Abrir en pantalla completaUna arena 3D con muros bajos y dos oleadas de enemigos. Ves a tu personaje desde atrás y apuntas con la mira del centro de la pantalla; los enemigos solo te disparan si te ven, así que agacharte tras un muro es defenderte, y ponerte de pie es el precio de disparar. Está hecha con threeplay, un motor 3D en la línea de Kaplay.
Hecha con threeplay, en unas 143 líneas de JavaScript.
Cómo está hecha
Configuración y controles
Se crea el juego a 640×360 y se definen los botones virtuales, entre ellos shoot y cover; los botones en pantalla del móvil pulsan esos mismos botones. FIRE_DELAY y WINDUP son los números que más cambian la dificultad, y WAVES lista dónde aparece cada enemigo.
const k = threeplay({ width: 640, height: 360, letterbox: true, background: "#9bb7c4", buttons: { left: { keyboard: ["left", "a"] }, right: { keyboard: ["right", "d"] }, up: { keyboard: ["up", "w"] }, down: { keyboard: ["down", "s"] }, shoot: { keyboard: ["space", "j"], mouse: "left" }, cover: { keyboard: ["shift", "c"], mouse: "right" }, }, }); touchControls(k, [ { button: "left", label: "◀" }, { button: "up", label: "▲" }, { button: "down", label: "▼" }, { button: "right", label: "▶" }, { button: "cover", label: "▽", side: "right" }, { button: "shoot", label: "✹", side: "right" }, ]); setGravity(30); const SPEED = 5; const COVER_SPEED = 2; // crouching is slow: you duck, you don't run const FIRE_DELAY = 2; // seconds between enemy shots const WINDUP = 0.7; // warning before an enemy fires: time to duck // Each wave is a list of [x, z] enemy spots. const WAVES = [ [[-8, -11], [0, -12], [8, -11]], [[-10, -9], [-4, -12], [4, -12], [10, -9]], ];La arena y las coberturas
La arena es un suelo, cuatro muros altos y una lista de muros bajos de 1,4 de alto. Cada uno lleva area() y body({ isStatic: true }), de modo que bloquean al personaje y también a los rayos. Su altura es diseño: de pie asomas la cabeza por encima, agachado no.
// [x, z, width, depth]: low walls (1.4 high). Standing you show over them; crouched you don't. const COVERS = [[-6, 3, 4, 1], [6, 3, 4, 1], [0, -2, 3, 1], [-10, -4, 1, 4], [10, -4, 1, 4], [0, 6, 6, 1]]; function buildArena() { add([box(32, 1, 32), pos(0, -0.5, 0), color("#8d8d80"), area(), body({ isStatic: true })]); for (const [x, z, w, d] of [[0, -16, 32, 1], [0, 16, 32, 1], [-16, 0, 1, 32], [16, 0, 1, 32]]) { add([box(w, 3, d), pos(x, 1.5, z), color("#5c677d"), area(), body({ isStatic: true })]); } for (const [x, z, w, d] of COVERS) { add([box(w, 1.4, d), pos(x, 0.7, z), color("#bc6c25"), area(), body({ isStatic: true }), "cover"]); } }El personaje y la cámara al hombro
El jugador es una cápsula con character() y health(5). thirdPerson() pone la cámara detrás y desplazada a la derecha con shoulder (al hombro, para que el personaje no tape la cruz) y la orbita con el ratón (con lockOnClick el puntero queda capturado al hacer clic). Mientras mantienes el botón cover, el personaje se encoge a la mitad (y su collider con él) y se mueve más despacio: es lo que lo oculta tras un muro.
const player = add([capsule(0.4, 1.6), pos(0, 1, 10), rotate(), scale(), color("#277da1"), area(), character(), health(5), "player"]); // Over the shoulder: the camera sits to the right, so the crosshair is not behind the player. const cam = thirdPerson(player, { distance: 4, height: 1.2, shoulder: 0.9, lockOnClick: !isTouchscreen() }); cam.yaw = 0; cam.pitch = 8; let crouched = false; onUpdate(() => { crouched = isButtonDown("cover"); player.scale.y = crouched ? 0.5 : 1; // the collider shrinks too: a lower body hides behind the wall const dir = inputDir(); player.move(dir.clone().multiplyScalar(crouched ? COVER_SPEED : SPEED)); if (dir.lengthSq() > 0) player.lookAt(player.worldPos().add(dir)); });Disparar con la mira
El disparo es un raycast desde la cámara en la dirección en la que mira, que coincide con la cruz del centro de la pantalla. Lo primero que toca recibe el daño: un muro lo frena, un enemigo pierde vida. Si estás agachado el disparo no sale, así que cada disparo exige asomarse. Un trazador breve muestra por dónde fue.
// Hitscan from the camera through the screen center, where the crosshair is. function tracer(from, to, tint) { const mid = from.clone().add(to).multiplyScalar(0.5); const line = add([box(0.05, 0.05, from.distanceTo(to)), pos(mid), rotate(), color(tint)]); line.lookAt(to); wait(0.06, () => line.exists() && destroy(line)); } onButtonPress("shoot", () => { if (crouched) return; // you must stand up (peek) to shoot beep({ freq: 200, slideTo: 70, duration: 0.1, type: "sawtooth" }); const from = camPos(); const hit = raycast(from, camera3d.getWorldDirection(vec3()), 60, { exclude: [player] }); const end = hit ? hit.point : from.clone().add(camera3d.getWorldDirection(vec3()).multiplyScalar(60)); tracer(player.worldPos().add(vec3(0, 0.4, 0)), end, "#ffd166"); if (hit?.obj.is("enemy")) hit.obj.hurt(1); });Enemigos con línea de visión
canSee() lanza un rayo desde los ojos del enemigo hasta la cabeza del jugador; solo cuenta si lo primero que toca es el jugador, no un muro. Cuando te ve, el enemigo se pone blanco (aviso de WINDUP) y dispara al terminar, volviendo a comprobar la visión: tienes un instante para agacharte. Los mismos muros que protegen al jugador protegen a los enemigos de su mirada.
// An enemy only fires if a ray from its eyes reaches the player's head: cover blocks it. function canSee(enemy) { const from = enemy.worldPos().add(vec3(0, 0.7, 0)); const head = player.worldPos().add(vec3(0, 0.7 * player.scale.y, 0)); const hit = raycast(from, head.sub(from), 40, { exclude: [enemy] }); return hit?.obj === player; } function addEnemy([x, z]) { const enemy = add([box(1, 1.8, 1), pos(x, 0.9, z), rotate(), color("#c1121f"), area(), body({ isStatic: true }), health(2), "enemy"]); enemy.aiming = false; enemy.cooldown = rand(0.5, FIRE_DELAY); return enemy; } function fire(enemy) { enemy.aiming = false; enemy.color.set("#c1121f"); if (!enemy.exists()) return; const from = enemy.worldPos().add(vec3(0, 0.7, 0)); beep({ freq: 140, slideTo: 50, duration: 0.12, type: "square" }); if (canSee(enemy)) { tracer(from, player.worldPos(), "#ff595e"); player.hurt(1); camShake(0.15, 0.25); } } onUpdate("enemy", (e) => { e.lookAt(vec3(player.pos.x, e.pos.y, player.pos.z)); e.cooldown -= dt(); if (e.aiming || e.cooldown > 0 || !canSee(e)) return; e.aiming = true; e.cooldown = FIRE_DELAY; e.color.set("#ffffff"); // the warning wait(WINDUP, () => fire(e)); }); on("death", "enemy", (e) => { destroy(e); beep({ freq: 400, slideTo: 100, duration: 0.2 }); if (get("enemy").length === 0) nextWave(); }); player.onDeath(() => go("end", false));Oleadas
Cuando muere el último enemigo se crea la siguiente oleada de WAVES; al terminar la última, ganas. Pocas oleadas cortas bastan para repetir el ciclo agacharse, asomarse, disparar y volver a cubrirse.
let wave = 0; function nextWave() { if (wave >= WAVES.length) return wait(0.5, () => go("end", true)); for (const spot of WAVES[wave++]) addEnemy(spot); updateHud(); }El marcador
Los textos con fixed() van en la pantalla, no en el mundo. Muestran la vida, la oleada y una pista de controles, y la cruz del centro es un texto más. player.onHurt() actualiza el marcador cada vez que te hieren.
const hud = add([text("", { size: 16, font: FONT }), pos(12, 10), fixed()]); const hint = add([text("", { size: 13, font: FONT }), pos(12, 340), anchor("botleft"), fixed()]); add([text("+", { size: 22, font: FONT }), pos(320, 180), anchor("center"), fixed()]); hint.text = t({ es: "Agáchate (Shift) para cubrirte; ponte de pie para disparar", en: "Crouch (Shift) to take cover; stand up to shoot" }); function updateHud() { hud.text = `${t({ es: "Vida", en: "Health" })} ${player.hp} ${t({ es: "Oleada", en: "Wave" })} ${wave}/${WAVES.length}`; } player.onHurt(updateHud); nextWave();Escenas
Tres escenas (title, game y end) y go() para pasar de una a otra; la de fin recibe si ganaste o perdiste. La pantalla de título reutiliza la arena con una cámara que orbita sola.
function screen(title, subtitle) { add([text(title, { size: 38, font: FONT }), pos(320, 140), anchor("center"), fixed()]); add([text(subtitle, { size: 15, font: FONT }), pos(320, 190), anchor("center"), fixed()]); add([text(t({ es: "Clic o espacio para jugar", en: "Click or space to play" }), { size: 15, font: FONT }), pos(320, 240), anchor("center"), fixed()]); onButtonPress("shoot", () => go("game")); } scene("title", () => { buildArena(); orbitCamera({ distance: 24, autoRotate: 10, interactive: false }); screen(t({ es: "Disparos en tercera persona", en: "Third-person shooter" }), t({ es: "Cúbrete tras los muros, asómate, dispara y vuelve a cubrirte", en: "Duck behind the walls, peek out, shoot and duck again" })); }); scene("end", (won) => { unlockPointer(); screen(won ? t({ es: "¡Arena despejada!", en: "Arena cleared!" }) : t({ es: "Te derribaron", en: "You were taken down" }), ""); }); go("title");
Qué simplificamos
- Los enemigos no se mueven, no buscan cobertura ni flanquean; solo giran hacia ti y disparan cuando te ven.
- Agacharse reduce la escala del personaje y la altura que miran los enemigos, pero no hay animaciones ni un sistema de cobertura que te pegue al muro.
- Todos los disparos son instantáneos (hitscan), sin munición ni recarga; la vida es un número entero y no se recupera.
Para modificarla
- Haz que un enemigo se desplace de un muro a otro cuando lo hieras, en lugar de quedarse quieto.
- Agrega munición limitada con recarga, de modo que asomarse tenga también un costo en tiempo.
- Añade una pequeña dispersión al disparo que aumente al moverte y disminuya al agacharte.
Código completo
import threeplay from "../../vendor/threeplay/threeplay.mjs";
import { FONT, t, touchControls } from "../common.js";
// #region setup
const k = threeplay({
width: 640,
height: 360,
letterbox: true,
background: "#9bb7c4",
buttons: {
left: { keyboard: ["left", "a"] },
right: { keyboard: ["right", "d"] },
up: { keyboard: ["up", "w"] },
down: { keyboard: ["down", "s"] },
shoot: { keyboard: ["space", "j"], mouse: "left" },
cover: { keyboard: ["shift", "c"], mouse: "right" },
},
});
touchControls(k, [
{ button: "left", label: "◀" },
{ button: "up", label: "▲" },
{ button: "down", label: "▼" },
{ button: "right", label: "▶" },
{ button: "cover", label: "▽", side: "right" },
{ button: "shoot", label: "✹", side: "right" },
]);
setGravity(30);
const SPEED = 5;
const COVER_SPEED = 2; // crouching is slow: you duck, you don't run
const FIRE_DELAY = 2; // seconds between enemy shots
const WINDUP = 0.7; // warning before an enemy fires: time to duck
// Each wave is a list of [x, z] enemy spots.
const WAVES = [
[[-8, -11], [0, -12], [8, -11]],
[[-10, -9], [-4, -12], [4, -12], [10, -9]],
];
// #endregion
// #region arena
// [x, z, width, depth]: low walls (1.4 high). Standing you show over them; crouched you don't.
const COVERS = [[-6, 3, 4, 1], [6, 3, 4, 1], [0, -2, 3, 1], [-10, -4, 1, 4], [10, -4, 1, 4], [0, 6, 6, 1]];
function buildArena() {
add([box(32, 1, 32), pos(0, -0.5, 0), color("#8d8d80"), area(), body({ isStatic: true })]);
for (const [x, z, w, d] of [[0, -16, 32, 1], [0, 16, 32, 1], [-16, 0, 1, 32], [16, 0, 1, 32]]) {
add([box(w, 3, d), pos(x, 1.5, z), color("#5c677d"), area(), body({ isStatic: true })]);
}
for (const [x, z, w, d] of COVERS) {
add([box(w, 1.4, d), pos(x, 0.7, z), color("#bc6c25"), area(), body({ isStatic: true }), "cover"]);
}
}
// #endregion
scene("game", () => {
buildArena();
// #region player
const player = add([capsule(0.4, 1.6), pos(0, 1, 10), rotate(), scale(), color("#277da1"), area(), character(), health(5), "player"]);
// Over the shoulder: the camera sits to the right, so the crosshair is not behind the player.
const cam = thirdPerson(player, { distance: 4, height: 1.2, shoulder: 0.9, lockOnClick: !isTouchscreen() });
cam.yaw = 0;
cam.pitch = 8;
let crouched = false;
onUpdate(() => {
crouched = isButtonDown("cover");
player.scale.y = crouched ? 0.5 : 1; // the collider shrinks too: a lower body hides behind the wall
const dir = inputDir();
player.move(dir.clone().multiplyScalar(crouched ? COVER_SPEED : SPEED));
if (dir.lengthSq() > 0) player.lookAt(player.worldPos().add(dir));
});
// #endregion
// #region shooting
// Hitscan from the camera through the screen center, where the crosshair is.
function tracer(from, to, tint) {
const mid = from.clone().add(to).multiplyScalar(0.5);
const line = add([box(0.05, 0.05, from.distanceTo(to)), pos(mid), rotate(), color(tint)]);
line.lookAt(to);
wait(0.06, () => line.exists() && destroy(line));
}
onButtonPress("shoot", () => {
if (crouched) return; // you must stand up (peek) to shoot
beep({ freq: 200, slideTo: 70, duration: 0.1, type: "sawtooth" });
const from = camPos();
const hit = raycast(from, camera3d.getWorldDirection(vec3()), 60, { exclude: [player] });
const end = hit ? hit.point : from.clone().add(camera3d.getWorldDirection(vec3()).multiplyScalar(60));
tracer(player.worldPos().add(vec3(0, 0.4, 0)), end, "#ffd166");
if (hit?.obj.is("enemy")) hit.obj.hurt(1);
});
// #endregion
// #region enemies
// An enemy only fires if a ray from its eyes reaches the player's head: cover blocks it.
function canSee(enemy) {
const from = enemy.worldPos().add(vec3(0, 0.7, 0));
const head = player.worldPos().add(vec3(0, 0.7 * player.scale.y, 0));
const hit = raycast(from, head.sub(from), 40, { exclude: [enemy] });
return hit?.obj === player;
}
function addEnemy([x, z]) {
const enemy = add([box(1, 1.8, 1), pos(x, 0.9, z), rotate(), color("#c1121f"), area(), body({ isStatic: true }), health(2), "enemy"]);
enemy.aiming = false;
enemy.cooldown = rand(0.5, FIRE_DELAY);
return enemy;
}
function fire(enemy) {
enemy.aiming = false;
enemy.color.set("#c1121f");
if (!enemy.exists()) return;
const from = enemy.worldPos().add(vec3(0, 0.7, 0));
beep({ freq: 140, slideTo: 50, duration: 0.12, type: "square" });
if (canSee(enemy)) {
tracer(from, player.worldPos(), "#ff595e");
player.hurt(1);
camShake(0.15, 0.25);
}
}
onUpdate("enemy", (e) => {
e.lookAt(vec3(player.pos.x, e.pos.y, player.pos.z));
e.cooldown -= dt();
if (e.aiming || e.cooldown > 0 || !canSee(e)) return;
e.aiming = true;
e.cooldown = FIRE_DELAY;
e.color.set("#ffffff"); // the warning
wait(WINDUP, () => fire(e));
});
on("death", "enemy", (e) => {
destroy(e);
beep({ freq: 400, slideTo: 100, duration: 0.2 });
if (get("enemy").length === 0) nextWave();
});
player.onDeath(() => go("end", false));
// #endregion
// #region waves
let wave = 0;
function nextWave() {
if (wave >= WAVES.length) return wait(0.5, () => go("end", true));
for (const spot of WAVES[wave++]) addEnemy(spot);
updateHud();
}
// #endregion
// #region hud
const hud = add([text("", { size: 16, font: FONT }), pos(12, 10), fixed()]);
const hint = add([text("", { size: 13, font: FONT }), pos(12, 340), anchor("botleft"), fixed()]);
add([text("+", { size: 22, font: FONT }), pos(320, 180), anchor("center"), fixed()]);
hint.text = t({ es: "Agáchate (Shift) para cubrirte; ponte de pie para disparar", en: "Crouch (Shift) to take cover; stand up to shoot" });
function updateHud() {
hud.text = `${t({ es: "Vida", en: "Health" })} ${player.hp} ${t({ es: "Oleada", en: "Wave" })} ${wave}/${WAVES.length}`;
}
player.onHurt(updateHud);
nextWave();
// #endregion
});
// #region scenes
function screen(title, subtitle) {
add([text(title, { size: 38, font: FONT }), pos(320, 140), anchor("center"), fixed()]);
add([text(subtitle, { size: 15, font: FONT }), pos(320, 190), anchor("center"), fixed()]);
add([text(t({ es: "Clic o espacio para jugar", en: "Click or space to play" }), { size: 15, font: FONT }), pos(320, 240), anchor("center"), fixed()]);
onButtonPress("shoot", () => go("game"));
}
scene("title", () => {
buildArena();
orbitCamera({ distance: 24, autoRotate: 10, interactive: false });
screen(t({ es: "Disparos en tercera persona", en: "Third-person shooter" }), t({ es: "Cúbrete tras los muros, asómate, dispara y vuelve a cubrirte", en: "Duck behind the walls, peek out, shoot and duck again" }));
});
scene("end", (won) => {
unlockPointer();
screen(won ? t({ es: "¡Arena despejada!", en: "Arena cleared!" }) : t({ es: "Te derribaron", en: "You were taken down" }), "");
});
go("title");
// #endregionHistoria
- 1996Origen
Tomb Raider (1996) se considera en gran parte responsable de la popularidad del género, aunque antes hubo arcades con vista desde la espalda, como Space Harrier (1985).
Third-person shooter (Wikipedia) - 2005
Resident Evil 4 impone la cámara sobre el hombro.
Third-person shooter (Wikipedia) - 2006
Gears of War combina coberturas con una cámara descentrada, influido por Kill Switch y Resident Evil 4.
Third-person shooter (Wikipedia)
Juegos de referencia
2001
Max Payne
Un policía de Nueva York investiga el asesinato de su familia en una historia de cine negro contada con viñetas de novela gráfica. Fue de los primeros juegos con tiempo bala, que ralentiza la acción para apuntar mientras saltas.
2006
Gears of War
Disparos en tercera persona en los que cubrirse es la base de todo: te pegas a un muro, te asomas a disparar y corres a la siguiente cobertura. Al recargar, pulsar en el momento justo te da balas más potentes.