/** * Héroe jugable: control de plataformas, vida, combate, EmojiPowers y herramientas. * * Controles (ver informe/CLAUDE.md): * - jump: salto variable (+ coyote, buffer, doble salto). abajo + jump sobre plataforma oneWay = bajar. * - attack: combo de 3 golpes en suelo; en el aire con abajo = golpe en picado (rebota sobre enemigos). * - special: habilidad del poder activo (FURIA embestida, HIELO aliento, FUEGO bola, COOL onda). * - tool: burbuja-plataforma; con pistola de agua: tool + arriba (o de pie sobre una burbuja) dispara agua. * Si solo se tiene la pistola, tool dispara siempre agua. Mantener tool = ráfaga. * - dig: cava con la pala sobre un Area 'soft' (evento 'hero:dig'). * - nextPower/prevPower/power1..5: cambian entre los poderes desbloqueados. */ import * as THREE from 'three'; import { Entity } from '../../core/entity'; import type { Game } from '../../core/game'; import { approach, clamp, rand } from '../../core/math'; import type { Area, Body, Collider, Element, HeroApi, Hit, PowerId, ToolId, Vec2 } from '../../core/types'; import { Chibi } from '../../characters/chibi'; import type { Accessory, Expression } from '../../characters/types'; import { strike } from './strike'; import { SLOTS, autoAssignSlots, isToolOn, isSwitchTool, slotTool, toolOnFlag } from '../../core/slots'; import { blobShadow } from '../../render/materials'; import { vfxAmbient } from '../../vfx/index'; import { ICE_BLOCK } from './projectiles'; import { isRainingAt } from '../../world/weather'; declare module '../../core/types' { interface GameEvents { /** * El héroe cavó (pies en x, y). `target` es la celda de tierra (`tag: 'dig'`) que se retira; * `dir` indica si se cavó hacia abajo o hacia delante. `area` se conserva para las zonas antiguas * que aún usan parches `soft`. */ 'hero:dig': { x: number; y: number; area?: Area; target?: Collider; dir?: 'down' | 'forward' }; /** Herramienta de interruptor cambiada (linterna, lluvia). */ 'tool:toggle': { tool: 'flashlight' | 'rain'; on: boolean }; /** Onda COOL: permite a las zonas encender interruptores fríos cercanos. */ 'hero:coolwave': { x: number; y: number; radius: number }; } } // ───────────────────────────── Tuning ───────────────────────────── export const TUNING = { body: { hw: 0.36, hh: 0.5 }, move: { runSpeed: 7.6, groundAccel: 75, groundDecel: 85, turnAccel: 130, airAccel: 48, airDecel: 16, iceAccel: 13, iceDecel: 3.5, hurtFriction: 12, }, jump: { vel: 15.2, doubleVel: 12.8, airJumps: 1, gravity: 42, fallMul: 1.5, cutMul: 2.6, apexMul: 0.55, apexThreshold: 2.2, maxFall: 24, coyote: 0.1, buffer: 0.13, dropThrough: 0.25, cornerCorrection: 0.26, }, hp: { invuln: 1.3, stun: 0.28, knock: 7.5, knockY: 7.5, hitstop: 0.09, shake: 0.4, deadTime: 1.0, respawnInvuln: 1.6 }, fall: { damage: 1, resetDelay: 0.65, belowMinY: 1.5 }, attack: { duration: [0.26, 0.26, 0.36], activeAt: [0.07, 0.07, 0.11], damage: [1, 1, 2], knock: [6, 6, 10], reach: 0.78, lunge: [2.5, 2.5, 4.5], comboGrace: 0.28, hitstop: 0.05, moveMul: 0.3, }, dive: { speed: 17, bounce: 13.5, damage: 2 }, fury: { damageMul: 2, knockMul: 1.6, dashTime: 0.32, dashSpeed: 17, dashDamage: 2, stun: 0.9, cooldown: 0.65 }, ice: { breathTime: 0.5, range: 2.6, freeze: 3, damage: 1, cooldown: 0.75, hoverFall: 2.5 }, fire: { cooldown: 0.32, maxActive: 2, speed: 11, vy: 3.5, gravity: 24, bounceVy: 7.5, bounces: 3, life: 1.8, damage: 2 }, cool: { cooldown: 6, radius: 6.5, stun: 3.5 }, water: { rate: 0.13, speed: 15, gravity: 7, life: 0.5, damage: 1, aimRange: 7, aimUp: 1.05, aimDown: 0.6 }, bubble: { max: 3, life: 5.5, maxBounces: 3, radius: 0.6, groundAhead: 1.5, airAhead: 0.5, airBelow: 0.75, cooldown: 0.22, popHop: 9 }, dig: { time: 0.55 }, fx: { stepEvery: 0.27, dustEvery: 0.15, landDust: 6 }, }; const T = TUNING; const POWER_ORDER: PowerId[] = ['base', 'fury', 'ice', 'fire', 'cool']; interface Look { color: number; expr: Expression; acc: Accessory; emissive: number; ei: number; name: string; emoji: string; desc: string; } export const LOOKS: Record = { base: { color: 0xffcf24, expr: 'smile', acc: 'none', emissive: 0x000000, ei: 0, name: 'NORMAL', emoji: '🙂', desc: 'Equilibrado y valiente' }, fury: { color: 0xf2452e, expr: 'angry', acc: 'steam', emissive: 0xff2000, ei: 0.12, name: 'FURIA', emoji: '😡', desc: 'Especial: embestida que rompe bloques' }, ice: { color: 0xa9daf7, expr: 'cold', acc: 'iceCrown', emissive: 0x2a8cff, ei: 0.06, name: 'HIELO', emoji: '🥶', desc: 'Especial: aliento helado que congela' }, fire: { color: 0xff8a1e, expr: 'fierce', acc: 'flameHair', emissive: 0xff5a00, ei: 0.18, name: 'FUEGO', emoji: '🔥', desc: 'Especial: bola de fuego rebotona' }, cool: { color: 0xffcf24, expr: 'cool', acc: 'sunglasses', emissive: 0x000000, ei: 0, name: 'COOL', emoji: '😎', desc: 'Especial: onda que detiene a los enemigos' }, }; const TOOLS: Record = { bubbles: { name: 'BURBUJAS', emoji: '🫧', desc: 'Herramienta: crea burbujas para cruzar abismos y lagunas' }, flashlight: { name: 'LINTERNA', emoji: '🔦', desc: 'Interruptor: enciende y apaga la iluminación de la cueva' }, shovel: { name: 'PALA', emoji: '🪏', desc: 'Cava en el suelo blando' }, rain: { name: 'LLUVIA', emoji: '🌧️', desc: 'Interruptor: activa y desactiva la lluvia' }, watergun: { name: 'PISTOLA DE AGUA', emoji: '🔫', desc: 'Dispara chorros de agua que dañan enemigos, sobre todo voladores; mantén pulsado para un chorro continuo' }, }; // ───────────────────────────── Héroe ───────────────────────────── export class Hero extends Entity implements HeroApi { declare body: Body; /** Profundidad visual: el héroe va 0,5 u por delante del plano de juego (z=0) * para que siempre se dibuje EN PRIMER PLANO al solaparse con un NPC, un cofre * o un enemigo (todos en z=0). A 26 u de la cámara el cambio de tamaño es del * 2 %, imperceptible; la física es 2D (x/y) y no se ve afectada. */ override z = 0.5; facing: 1 | -1 = 1; inputLocked = false; readonly rig: Chibi; /** Luz compartida (bolas de fuego / aura de fuego). Siempre en escena para no recompilar shaders. */ readonly fireLight = new THREE.PointLight(0xff8a2a, 0, 7, 1.6); private shadow: THREE.Mesh; private hiddenDeath = false; private _power: PowerId = 'base'; private _alive = true; private coyote = 0; private buffer = 0; private airJumps = 0; private wasGround = true; private prevVy = 0; private hurtT = 0; private invuln = 0; private deadT = 0; private respawning = false; private fallResetT = 0; private lastSafe: Vec2 = { x: 0, y: 0 }; private attackT = 0; private attackStep = 0; private attackHit = false; private attackQueued = false; private comboT = 0; private diving = false; private dashT = 0; private breathT = 0; private specialCd = 0; private toolCd = 0; private digT = 0; private readonly hitSet = new Set(); private stepT = 0; private dustT = 0; private exprT = 0; constructor() { super(); this.team = 'hero'; this.persistent = true; this.tags.add('hero'); this.rig = new Chibi({ color: LOOKS.base.color, expression: 'smile' }); this.view.add(this.rig.root); this.shadow = blobShadow(0.45, 0.38); this.view.add(this.shadow); this.hp = 6; } get power(): PowerId { return this._power; } get alive(): boolean { return this._alive; } /** true solo mientras la linterna está encendida con su interruptor. */ get flashlight(): boolean { return isToolOn(this.game.state, 'flashlight'); } get specialCooldown(): number { return this.specialCd; } onAdded(): void { this.body = this.game.physics.body(this.x, this.y + T.body.hh, T.body.hw, T.body.hh); this.x = this.px = this.body.x; this.y = this.py = this.body.y; this.lastSafe = { x: this.x, y: this.y - T.body.hh }; this.game.hero = this; this.game.gfx.cam.follow(this); this.game.gfx.scene.add(this.fireLight); const st = this.game.state; if (st.data.hp <= 0) st.data.hp = st.data.maxHp; const p = st.data.power; this._power = st.hasPower(p) ? p : 'base'; this.applyLook(false); // La mochila llega como regalo de Emma (flag hero.backpack); al cargar partida se reaplica. this.offs.push( this.game.events.on('state:changed', () => { this.refreshOutfit(); autoAssignSlots(this.game.state); }), this.game.events.on('flag', (e) => { if (e.key === 'hero.backpack' && e.value && !e.prev) this.receiveBackpack(); }), ); } onRemoved(): void { for (const off of this.offs) off(); this.offs.length = 0; this.fireLight.parent?.remove(this.fireLight); this.rig.dispose(); if (this.game.hero === this) this.game.hero = null; } // ───────── bucle ───────── update(dt: number): void { const b = this.body; const g = this.game; if (!g.state.hasPower(this._power)) { this._power = 'base'; g.state.data.power = 'base'; this.applyLook(false); } const inp = g.input; this.invuln = Math.max(0, this.invuln - dt); this.specialCd = Math.max(0, this.specialCd - dt); this.toolCd = Math.max(0, this.toolCd - dt); this.hurtT = Math.max(0, this.hurtT - dt); this.comboT = Math.max(0, this.comboT - dt); this.digT = Math.max(0, this.digT - dt); if (this.exprT > 0) { this.exprT -= dt; if (this.exprT <= 0 && this._alive) this.rig.setExpression(LOOKS[this._power].expr); } if (!this._alive) { b.vx = approach(b.vx, 0, 10 * dt); b.vy = Math.max(-T.jump.maxFall, b.vy - T.jump.gravity * dt); g.physics.move(b, dt); this.deadT += dt; if (this.deadT > T.hp.deadTime && !this.respawning) void this.respawn(); return; } if (this.fallResetT > 0) { this.fallResetT -= dt; if (this.fallResetT <= 0) this.finishFallReset(); return; } const ctl = !this.inputLocked && this.hurtT <= 0; const ax = ctl ? inp.axisX : 0; const busy = this.attackT > 0 || this.dashT > 0 || this.breathT > 0 || this.digT > 0; if (ax && !busy) this.facing = ax > 0 ? 1 : -1; if (ctl) this.handlePowerInput(); // ── Horizontal const ground = b.onGround ? b.ground : null; const ice = ground?.material === 'ice'; if (this.dashT > 0) { this.updateDash(dt); } else if (this.hurtT > 0) { b.vx = approach(b.vx, 0, T.move.hurtFriction * dt); } else { let mul = 1; if (this.attackT > 0 && b.onGround) mul = T.attack.moveMul; if (this.digT > 0) mul = 0; const target = ax * T.move.runSpeed * mul; let rate: number; if (b.onGround) { if (target === 0) rate = ice ? T.move.iceDecel : T.move.groundDecel; else if (ice) rate = T.move.iceAccel; else rate = b.vx !== 0 && Math.sign(target) !== Math.sign(b.vx) ? T.move.turnAccel : T.move.groundAccel; } else rate = target === 0 ? T.move.airDecel : T.move.airAccel; b.vx = approach(b.vx, target, rate * dt); } // ── Salto this.coyote = b.onGround ? T.jump.coyote : this.coyote - dt; if (ctl && inp.pressed('jump')) this.buffer = T.jump.buffer; else this.buffer -= dt; if (b.onGround) { this.airJumps = 0; } if (this.buffer > 0 && this.dashT <= 0 && this.digT <= 0) { if (b.onGround && inp.held('down') && ground?.oneWay) { b.dropThrough = T.jump.dropThrough; b.vy = -2; this.buffer = 0; this.coyote = 0; } else if (this.coyote > 0) { this.doJump(T.jump.vel, false); } else if (this.airJumps < T.jump.airJumps) { this.airJumps++; this.doJump(T.jump.doubleVel, true); } } // ── Gravedad if (this.dashT <= 0) { let grav = T.jump.gravity; if (b.vy < 0) grav *= T.jump.fallMul; else if (b.vy > 0 && !inp.held('jump')) grav *= T.jump.cutMul; else if (inp.held('jump') && Math.abs(b.vy) < T.jump.apexThreshold) grav *= T.jump.apexMul; b.vy = Math.max(-T.jump.maxFall, b.vy - grav * dt); if (this.diving) b.vy = -T.dive.speed; if (this.breathT > 0 && b.vy < -T.ice.hoverFall) b.vy = -T.ice.hoverFall; } // ── Acciones if (ctl) { this.handleAttack(dt); this.handleSpecial(); this.handleSlots(); } else { this.attackQueued = false; } this.updateAttack(dt); this.updateBreath(dt); if (this.diving) this.updateDive(); // ── Movimiento this.cornerCorrect(dt); this.prevVy = b.vy; g.physics.move(b, dt); this.afterMove(dt); } private afterMove(dt: number): void { const b = this.body; const g = this.game; const feet = b.y - b.hh; // Aterrizaje if (b.onGround && !this.wasGround) { const impact = -this.prevVy; if (this.diving) { this.diving = false; g.gfx.cam.shake(0.25, 0.15); g.vfx.burst('land', b.x, feet, { count: 10, scale: 1.2 }); g.audio.sfx('land', { volume: 1, x: b.x }); } else if (impact > 4) { g.vfx.burst('dust', b.x, feet, { count: Math.round(T.fx.landDust * clamp(impact / 15, 0.4, 1.6)), scale: 0.8 }); g.audio.sfx('land', { volume: clamp(impact / 20, 0.2, 1), x: b.x }); if (impact > 18) { this.rig.squash(-0.15); g.gfx.cam.shake(0.12, 0.12); } } if (b.ground?.material === 'bubble') g.audio.sfx('bounce', { volume: 0.5, pitch: 1.3 }); } this.wasGround = b.onGround; // Polvo y pasos if (b.onGround && Math.abs(b.vx) > 4) { this.stepT -= dt; this.dustT -= dt; if (this.stepT <= 0) { this.stepT = T.fx.stepEvery; const mat = b.ground?.material; g.audio.sfx('step', { volume: 0.25, pitch: mat === 'ice' ? 1.3 : mat === 'metal' ? 1.15 : rand(0.92, 1.08), x: b.x }); } if (this.dustT <= 0) { this.dustT = T.fx.dustEvery; g.vfx.burst('dust', b.x - this.facing * 0.3, feet + 0.05, { count: 1, scale: 0.5, dirX: -this.facing }); } if (b.vx * this.facing < 0 && Math.abs(b.vx) > 5) { g.vfx.burst('dust', b.x + Math.sign(b.vx) * 0.35, feet + 0.05, { count: 1, scale: 0.6, dirX: Math.sign(b.vx) }); } } else { this.stepT = 0; } // Último suelo seguro const gr = b.ground; if (b.onGround && gr && gr.material !== 'bubble' && !('vx' in gr) && !('vy' in gr) && gr.owner === undefined) { const ph = g.physics; if (ph.groundBelow(b.x - b.hw * 0.9, feet + 0.05, 0.25) !== null && ph.groundBelow(b.x + b.hw * 0.9, feet + 0.05, 0.25) !== null && ph.areasAt(b, 'hazard').length === 0) { this.lastSafe.x = b.x; this.lastSafe.y = feet; } } // Peligros, agua y caída for (const a of g.physics.areasAt(b, 'hazard')) { this.takeHit({ damage: a.data?.damage ?? 1, element: (a.data?.element as Element) ?? 'none', dirX: -this.facing, knock: 8 }); } const water = g.physics.areasAt(b, 'water').find((a) => !a.data?.swim && b.y < a.y + a.hh); if (water) { this.fallOut('water', water.y + water.hh); return; } // caer en la lava: quema y vuelve al último suelo seguro (como el agua) const lava = g.physics.areasAt(b, 'lava').find((a) => a.enabled !== false && b.y - b.hh < a.y + a.hh - 0.15); if (lava) { this.fallOut('lava', lava.y + lava.hh); return; } const minY = g.zone?.bounds.minY; if (minY !== undefined && b.y < minY - T.fall.belowMinY) this.fallOut('pit', minY); // Luz de fuego como aura cuando no hay bolas de fuego if (this._power === 'fire' && !this.fireLight.userData.busy) { this.fireLight.position.set(b.x, b.y + 0.4, 1.2); this.fireLight.intensity = 3; } else if (!this.fireLight.userData.busy) { this.fireLight.intensity = 0; } } private doJump(v: number, double: boolean): void { const b = this.body; const g = this.game; b.vy = v; this.buffer = 0; this.coyote = 0; this.diving = false; const feet = b.y - b.hh; if (double) { g.audio.sfx('doublejump', { x: b.x }); g.vfx.burst('sparkle', b.x, feet, { count: 6, scale: 0.7, color: LOOKS[this._power].color }); g.vfx.ring(b.x, feet, 0xffffff, 0.6); this.rig.squash(0.3); this.rig.play('victory', { speed: 2.6 }); } else { g.audio.sfx('jump', { x: b.x }); g.vfx.burst('dust', b.x, feet, { count: 3, scale: 0.6 }); this.rig.squash(0.35); } } /** Corrección de esquinas: si la cabeza roza un borde al subir, desliza un poco en X. */ private cornerCorrect(dt: number): void { const b = this.body; if (b.vy <= 0) return; const ph = this.game.physics; const solid = (c: { oneWay?: boolean }) => !c.oneWay; const probe = { x: b.x, y: b.y + b.vy * dt + 0.02, hw: b.hw, hh: b.hh }; if (!ph.query(probe, solid).length) return; for (let d = 0.05; d <= T.jump.cornerCorrection + 1e-6; d += 0.05) { for (const s of [-1, 1]) { probe.x = b.x + s * d; if (!ph.query(probe, solid).length) { b.x += s * d; return; } } } } // ───────── combate ───────── private handleAttack(_dt: number): void { const inp = this.game.input; const b = this.body; if (!inp.pressed('attack') || this.dashT > 0 || this.digT > 0) return; inp.consume('attack'); if (!b.onGround && inp.held('down')) { if (!this.diving) this.startDive(); return; } if (this.attackT > 0) { this.attackQueued = true; return; } const next = this.comboT > 0 && this.attackStep < 2 ? this.attackStep + 1 : 0; this.startAttack(next); } private startAttack(step: number): void { this.attackStep = step; this.attackT = T.attack.duration[step]; this.attackHit = false; this.attackQueued = false; const b = this.body; if (b.onGround) b.vx += this.facing * T.attack.lunge[step]; this.rig.play('attack', { speed: 0.3 / T.attack.duration[step] }); if (step === 2) this.rig.squash(0.2); this.game.audio.sfx('whoosh', { volume: 0.5, pitch: 1 + step * 0.12 }); if (this._power === 'base') this.tempExpr('determined', 0.4); } private updateAttack(dt: number): void { if (this.attackT <= 0) return; this.attackT -= dt; const step = this.attackStep; const elapsed = T.attack.duration[step] - this.attackT; if (!this.attackHit && elapsed >= T.attack.activeAt[step]) { this.attackHit = true; this.attackStrike(step); } if (this.attackT <= 0) { this.comboT = T.attack.comboGrace; if (this.attackQueued && step < 2) this.startAttack(step + 1); else if (step === 2) this.comboT = 0; } } private attackStrike(step: number): void { const g = this.game; const b = this.body; const fury = this._power === 'fury'; const reach = T.attack.reach + step * 0.08; const box = { x: b.x + this.facing * reach, y: b.y, hw: 0.55 + step * 0.08, hh: 0.52 }; const hit: Hit = { damage: T.attack.damage[step] * (fury ? T.fury.damageMul : 1), element: fury ? 'fury' : 'none', dirX: this.facing, knock: T.attack.knock[step] * (fury ? T.fury.knockMul : 1), stun: step === 2 ? 0.4 : 0.15, source: this, }; const hits = strike(g, box, hit, this); if (hits.length) { g.hitstop(T.attack.hitstop + step * 0.025 + (fury ? 0.02 : 0)); g.audio.sfx('punch', { pitch: 1 + step * 0.1, x: b.x }); g.gfx.cam.shake(0.12 + step * 0.08 + (fury ? 0.1 : 0), 0.12); for (const e of hits) { g.vfx.burst('hit', (b.x + e.x) / 2 + this.facing * 0.2, e.y, { dirX: this.facing, scale: 1 + step * 0.25, color: fury ? 0xff4020 : undefined }); if (step === 2) g.vfx.burst('star', e.x, e.y + 0.3, { count: 4 }); } } } private startDive(): void { const b = this.body; this.diving = true; this.hitSet.clear(); b.vx *= 0.3; b.vy = -T.dive.speed; this.attackT = 0; this.rig.play('special', { speed: 2 }); this.rig.squash(0.3); this.game.audio.sfx('whoosh', { pitch: 0.8 }); } private updateDive(): void { const g = this.game; const b = this.body; g.vfx.trail('spark', b.x, b.y + 0.3, { color: LOOKS[this._power].color, scale: 0.6 }); const box = { x: b.x, y: b.y - b.hh - 0.1, hw: b.hw + 0.12, hh: 0.35 }; const fury = this._power === 'fury'; const hits = strike(g, box, { damage: T.dive.damage * (fury ? T.fury.damageMul : 1), element: fury ? 'fury' : 'none', dirX: this.facing, knock: 4, stun: 0.5, source: this, }, this, this.hitSet); if (hits.length) { this.diving = false; b.vy = T.dive.bounce; this.airJumps = 0; g.hitstop(0.07); g.gfx.cam.shake(0.25, 0.15); g.audio.sfx('bounce'); g.audio.sfx('punch', { pitch: 0.9 }); g.vfx.burst('hit', b.x, b.y - b.hh, { scale: 1.3 }); g.vfx.ring(b.x, b.y - b.hh, 0xffffff, 0.8); this.rig.squash(0.4); this.rig.play('victory', { speed: 2.6 }); } } // ───────── poderes ───────── private handlePowerInput(): void { const inp = this.game.input; const owned = POWER_ORDER.filter((p) => this.game.state.hasPower(p)); if (inp.pressed('nextPower') || inp.pressed('prevPower')) { if (owned.length < 2) { this.game.audio.sfx('error', { volume: 0.4 }); return; } const dir = inp.pressed('nextPower') ? 1 : -1; const i = Math.max(0, owned.indexOf(this._power)); this.setPower(owned[(i + dir + owned.length) % owned.length]); return; } const keys = ['power1', 'power2', 'power3', 'power4', 'power5'] as const; for (let i = 0; i < keys.length; i++) { if (!inp.pressed(keys[i])) continue; const p = POWER_ORDER[i]; if (this.game.state.hasPower(p)) this.setPower(p); else this.game.audio.sfx('error', { volume: 0.4 }); } } setPower(p: PowerId): void { if (p !== 'base' && !this.game.state.hasPower(p)) return; if (p === this._power) return; this._power = p; this.dashT = 0; this.breathT = 0; const st = this.game.state; st.data.power = p; st.changed(); this.game.events.emit('hero:power', { power: p }); this.applyLook(true); } private offs: Array<() => void> = []; /** La mochila solo la lleva la forma base y solo después de que Emma la regala. */ private refreshOutfit(): void { const has = this.game.state.has('hero.backpack'); this.rig.setOutfit(this._power === 'base' && has ? 'backpack' : 'none'); } private receiveBackpack(): void { const g = this.game; this.refreshOutfit(); this.rig.flash(0xffffff, 0.35); this.rig.squash(0.4); this.rig.play('victory'); g.vfx.burst('powerup', this.x, this.y); g.audio.sfx('powerup'); void g.ui.reward({ kind: 'item', emoji: '🎒', name: 'Mochila de aventura', desc: 'Un regalo de Emma para el viaje, guarda monedas, diamantes y objetos', color: '#ff6b5a' }); } private applyLook(animate: boolean): void { const L = LOOKS[this._power]; const r = this.rig; r.setColor(L.color); r.setAccessory(L.acc); this.refreshOutfit(); r.setEmissive(L.emissive, L.ei); r.setExpression(L.expr, animate ? 0.2 : 0); if (!animate) return; const g = this.game; const b = this.body; r.flash(0xffffff, 0.35); r.squash(0.4); r.play('special', { speed: 1.8 }); g.audio.sfx('transform', { x: b.x }); g.vfx.burst('sparkle', b.x, b.y, { count: 14, color: L.color, scale: 1.1 }); g.vfx.burst('emoji', b.x, b.y + 0.7, { emoji: L.emoji, count: 1 }); g.vfx.ring(b.x, b.y, L.color, 1.2); g.hitstop(0.04); } private handleSpecial(): void { const g = this.game; const inp = g.input; if (!inp.pressed('special') || this.dashT > 0 || this.breathT > 0 || this.digT > 0) return; inp.consume('special'); if (this.specialCd > 0 || this._power === 'base') { g.audio.sfx('error', { volume: 0.35 }); return; } this.attackT = 0; this.diving = false; switch (this._power) { case 'fury': return this.startDash(); case 'ice': return this.startBreath(); case 'fire': return this.throwFireball(); case 'cool': return this.coolWave(); } } private startDash(): void { const g = this.game; this.dashT = T.fury.dashTime; this.specialCd = T.fury.cooldown; this.hitSet.clear(); this.rig.play('special', { speed: 0.45 / T.fury.dashTime }); this.rig.squash(-0.2); g.audio.sfx('dash', { x: this.x }); g.vfx.burst('dust', this.x - this.facing * 0.4, this.y - T.body.hh, { count: 4, dirX: -this.facing }); } private updateDash(dt: number): void { const g = this.game; const b = this.body; this.dashT -= dt; b.vx = this.facing * T.fury.dashSpeed; b.vy = 0; g.vfx.trail('fire', b.x - this.facing * 0.4, b.y, { color: 0xf2452e, scale: 0.9 }); const box = { x: b.x + this.facing * 0.45, y: b.y, hw: 0.65, hh: 0.52 }; const hits = strike(g, box, { damage: T.fury.dashDamage, element: 'fury', dirX: this.facing, knock: 13, stun: T.fury.stun, source: this, }, this, this.hitSet); if (hits.length) { g.hitstop(0.06); g.gfx.cam.shake(0.35, 0.18); g.audio.sfx('hit', { x: b.x }); for (const e of hits) { g.vfx.burst(e.tags.has('breakable') ? 'shatter' : 'hit', e.x, e.y, { dirX: this.facing, scale: 1.3, color: 0xff4020 }); } } if (b.onWall === this.facing) { this.dashT = 0; b.vx = -this.facing * 4; b.vy = 5; g.gfx.cam.shake(0.3, 0.15); g.audio.sfx('hit', { pitch: 0.8 }); g.vfx.burst('hit', b.x + this.facing * 0.5, b.y, { dirX: -this.facing }); this.rig.squash(-0.25); } if (this.dashT <= 0) { this.dashT = 0; b.vx = this.facing * T.move.runSpeed * 0.6; } } private startBreath(): void { if (isRainingAt(this.game, this.body.x, this.body.y)) this.makeIceBlock(); this.breathT = T.ice.breathTime; this.specialCd = T.ice.cooldown; this.hitSet.clear(); this.rig.play('special', { speed: 0.45 / T.ice.breathTime }); this.game.audio.sfx('freeze', { x: this.x }); this.game.audio.sfx('whoosh', { pitch: 1.4, volume: 0.6 }); } private updateBreath(dt: number): void { if (this.breathT <= 0) return; this.breathT -= dt; const g = this.game; const b = this.body; const f = this.facing; for (let i = 0; i < 2; i++) { const d = 0.6 + Math.random() * T.ice.range; g.vfx.trail('ice', b.x + f * d, b.y + 0.05 + (Math.random() - 0.5) * d * 0.35, { dirX: f, scale: 0.5 + d * 0.2, color: 0xbfeaff }); } // Cono: tres cajas crecientes const boxes = [ { x: b.x + f * 0.85, y: b.y, hw: 0.4, hh: 0.3 }, { x: b.x + f * 1.6, y: b.y, hw: 0.45, hh: 0.45 }, { x: b.x + f * 2.35, y: b.y, hw: 0.45, hh: 0.6 }, ]; for (const box of boxes) { const hits = strike(g, box, { damage: T.ice.damage, element: 'ice', dirX: f, knock: 1.5, stun: T.ice.freeze, source: this, }, this, this.hitSet); for (const e of hits) { g.vfx.burst('ice', e.x, e.y, { count: 10, scale: 1.1 }); g.audio.sfx('freeze', { pitch: 1.2, x: e.x }); g.hitstop(0.04); } } if (this.breathT <= 0) { g.vfx.burst('ice', b.x + f * T.ice.range, b.y, { count: 5, scale: 0.8, dirX: f }); } } /** * HIELO con LLUVIA activa: las gotas se congelan en un bloque sólido delante del héroe. * En el suelo, el bloque se apoya delante (muro/barrera); en el aire, aparece bajo los pies algo * adelantado (escalón para trepar). Si ya hay un bloque ahí, se apila encima. */ private makeIceBlock(): void { const g = this.game; const b = this.body; const f = this.facing; const feet = b.y - b.hh; let x = b.onGround ? b.x + f * 1.25 : b.x + f * 0.75; let y = b.onGround ? feet + 0.5 : feet - 0.55; x = Math.round(x * 2) / 2; // si cae junto a un chorro de vapor, se encaja encima para taparlo if (b.onGround) { for (const v of g.allByTag('vent')) { if (Math.abs(v.x - x) < 1.1 && Math.abs(v.y - feet) < 0.6) { x = v.x; break; } } } const blocks = g.allByTag('iceblock').filter((e) => !e.dead); // alinea con un bloque vecino para que las pilas queden rectas for (const e of blocks) if (Math.abs(e.x - x) < 0.6 && Math.abs(e.y - y) < 1.6) { x = e.x; break; } for (let i = 0; i < 4; i++) { const taken = blocks.some((e) => Math.abs(e.x - x) < 0.6 && Math.abs(e.y - y) < 0.6); if (!taken) break; y += 1; } // no dentro del terreno ni del héroe const solid = g.physics.query({ x, y, hw: 0.42, hh: 0.42 }, (c) => !c.oneWay && c.enabled !== false && c.tag !== 'iceblock').length > 0; const overHero = Math.abs(b.x - x) < b.hw + 0.45 && Math.abs(b.y - y) < b.hh + 0.45; if (solid || overHero) { g.audio.sfx('error', { volume: 0.3 }); return; } if (blocks.length >= ICE_BLOCK.max) { blocks.sort((a, c) => a.id - c.id); (blocks[0] as Entity & { melt?: () => void }).melt?.(); } g.spawn('hero.iceblock', x, y, {}); } private rainFireHint = -10; private throwFireball(): void { const g = this.game; const active = g.allByTag('herofire').length; if (active >= T.fire.maxActive) return; if (isRainingAt(g, this.body.x, this.body.y)) { // con lluvia la bola de fuego se apaga nada más salir this.specialCd = 0.4; const fx = this.body.x + this.facing * 0.6; g.vfx.burst('smoke', fx, this.body.y, { count: 8, scale: 0.7 }); g.audio.sfx('splash', { pitch: 1.5, volume: 0.4, x: fx }); if (g.time - this.rainFireHint > 4) { this.rainFireHint = g.time; g.vfx.floatText('¡La lluvia apaga el fuego!', this.body.x, this.body.y + 1.4, '#ffb070'); } return; } this.specialCd = T.fire.cooldown; const b = this.body; g.spawn('hero.fireball', b.x + this.facing * 0.55, b.y + 0.05, { dir: this.facing, hero: this }); this.rig.play('special', { speed: 2 }); this.rig.squash(-0.15); g.audio.sfx('fireball', { x: b.x }); g.vfx.burst('fire', b.x + this.facing * 0.6, b.y, { count: 5, dirX: this.facing, scale: 0.7 }); } private coolWave(): void { const g = this.game; const b = this.body; this.specialCd = T.cool.cooldown; this.rig.play('victory', { speed: 1.6 }); g.audio.sfx('cool', { x: b.x }); g.vfx.ring(b.x, b.y, 0x7fd8ff, 3); g.vfx.ring(b.x, b.y, 0xffc928, 2); g.vfx.burst('sparkle', b.x, b.y, { count: 18, scale: 1.4, color: 0x9fe8ff }); g.vfx.floatText('¡COOL!', b.x, b.y + 1.1, '#7fe3ff'); g.gfx.cam.shake(0.2, 0.2); g.events.emit('hero:coolwave', { x: b.x, y: b.y, radius: T.cool.radius }); const r2 = T.cool.radius * T.cool.radius; for (const e of g.entities) { if (e.dead || e.team !== 'enemy') continue; const dx = e.x - b.x, dy = e.y - b.y; if (dx * dx + dy * dy > r2) continue; if (e.takeHit({ damage: 0, element: 'cool', dirX: dx < 0 ? -1 : 1, knock: 0, stun: T.cool.stun, source: this })) { g.vfx.burst('emoji', e.x, e.y + 0.7, { emoji: '💤', count: 1 }); } } } // ───────── herramientas ───────── /** Botones de herramienta asignables (mochila): cada uno usa la herramienta de su ranura. */ private handleSlots(): void { const g = this.game; const inp = g.input; for (const slot of SLOTS) { const pressed = inp.pressed(slot); const held = inp.held(slot); if (!pressed && !held) continue; const tool = slotTool(g.state, slot); if (!tool) { if (pressed) g.audio.sfx('error', { volume: 0.3 }); continue; } switch (tool) { case 'bubbles': if (pressed && this.toolCd <= 0) this.makeBubble(); break; case 'watergun': if (this.toolCd <= 0) this.shootWater(); break; case 'shovel': if (pressed) this.digNow(); break; case 'flashlight': case 'rain': if (pressed) this.toggleToolSwitch(tool); break; } } } /** Interruptores de herramienta: se encienden/apagan sin repetir mientras se mantiene el botón. */ private toggleToolSwitch(tool: 'flashlight' | 'rain'): void { const g = this.game; if (!isSwitchTool(tool)) return; const on = !isToolOn(g.state, tool); g.state.set(toolOnFlag(tool), on); g.state.changed(); g.state.save(); g.events.emit('tool:toggle', { tool, on }); this.rig.play('special', { speed: 2.7 }); this.rig.squash(0.22); if (tool === 'flashlight') { g.audio.sfx(on ? 'powerup' : 'ui_back', { volume: on ? 0.45 : 0.7 }); g.vfx.burst('sparkle', this.x, this.y + 0.9, { count: on ? 14 : 8, color: 0xffe066, scale: on ? 1.2 : 0.8 }); g.ui.toast(on ? 'Linterna encendida' : 'Linterna apagada', '🔦'); } else { g.audio.sfx(on ? 'rain' : 'whoosh', { volume: 0.55, pitch: on ? 1 : 1.3 }); vfxAmbient(g, on ? 'rain' : null, on ? { density: 0.55 } : undefined); g.vfx.burst('splash', this.x, this.y + 1.5, { count: on ? 14 : 6, color: 0x7fd0ff }); g.ui.toast(on ? 'Lluvia activada' : 'Lluvia desactivada', '🌧️'); } g.state.changed(); } private shootWater(): void { const g = this.game; const b = this.body; const up = g.input.held('up'); this.toolCd = T.water.rate; g.spawn('hero.water', b.x + this.facing * 0.5, b.y + (up ? 0.25 : 0.02), { dir: this.facing, up }); g.audio.sfx('water_shot', { volume: 0.6, pitch: rand(0.9, 1.1), x: b.x }); if (this.rig.anim !== 'special') this.rig.play('special', { speed: 3 }); } private rainBubbleHint = -10; private makeBubble(): void { const g = this.game; const b = this.body; if (isRainingAt(g, b.x, b.y)) { // la lluvia revienta las burbujas al instante this.toolCd = 0.4; g.audio.sfx('pop', { x: b.x, pitch: 1.4, volume: 0.6 }); g.vfx.burst('bubble', b.x + this.facing * 0.8, b.y, { count: 5, scale: 0.5 }); if (g.time - this.rainBubbleHint > 4) { this.rainBubbleHint = g.time; g.vfx.floatText('¡La lluvia revienta las burbujas!', b.x, b.y + 1.4, '#9fdcff'); } return; } const R = T.bubble.radius; const list = g.allByTag('herobubble'); if (list.length >= T.bubble.max) { list.sort((a, c) => a.id - c.id); (list[0] as Entity & { pop?: () => void }).pop?.(); } const feet = b.y - b.hh; let cx: number, cy: number; if (b.onGround) { cx = b.x + this.facing * T.bubble.groundAhead; cy = feet - R * 0.7; if (g.physics.solidAt(cx, cy) || g.physics.solidAt(cx, cy - R * 0.5)) cy = feet + R; } else { cx = b.x + this.facing * T.bubble.airAhead + b.vx * 0.05; cy = feet - T.bubble.airBelow; } this.toolCd = T.bubble.cooldown; g.spawn('tool.bubble', cx, cy, { dir: this.facing }); g.audio.sfx('bubble', { x: cx }); g.vfx.burst('bubble', cx, cy, { count: 6, scale: 0.7 }); this.rig.play('special', { speed: 2.4 }); } private digNow(): void { const g = this.game; const b = this.body; if (!b.onGround || this.digT > 0) return; this.digT = T.dig.time; const feet = b.y - b.hh; this.rig.play('dig'); this.rig.squash(0.18); g.audio.sfx('dig', { x: b.x }); // 1) Hacia abajo: si pisamos tierra excavable, esa celda es la prioridad. const down = { x: b.x, y: feet - 0.42, hw: 0.3, hh: 0.36 }; // 2) Hacia delante: muro de tierra a la altura de los pies. const fwd = { x: b.x + this.facing * 0.9, y: feet + 0.55, hw: 0.34, hh: 0.56 }; let target = g.physics.query(down, (c) => c.tag === 'dig')[0]; let dir: 'down' | 'forward' = 'down'; if (!target) { target = g.physics.query(fwd, (c) => c.tag === 'dig')[0]; dir = 'forward'; } if (target) { const tx = target.x; const ty = target.y; g.vfx.burst('dust', tx, ty, { count: 14, scale: 1.25, color: 0x9a6a3a }); g.vfx.burst('sparkle', tx, ty + 0.2, { count: 6, color: 0xffe066 }); g.gfx.cam.shake(0.12, 0.12); g.events.emit('hero:dig', { x: tx, y: ty, target, dir }); return; } // Pared de roca normal: no se puede cavar. Rebote cómico + aviso. const rock = g.physics.query(fwd, (c) => c.material === 'stone' || c.material === 'metal')[0] ?? g.physics.query(down, (c) => c.material === 'stone' || c.material === 'metal')[0]; if (rock) { b.vx = -this.facing * 5.5; b.vy = Math.max(b.vy, 3.4); g.audio.sfx('bounce', { pitch: 1.5, volume: 0.55, x: b.x }); g.vfx.burst('spark', rock.x, rock.y, { count: 7, color: 0xd8d2c0, dirX: this.facing }); g.vfx.floatText('¡Roca dura! Aquí no se puede cavar', b.x, b.y + 1.1, '#ffe3a8'); g.gfx.cam.shake(0.16, 0.16); this.rig.play('hurt'); this.rig.squash(-0.22); return; } // Compatibilidad con las zonas antiguas: parche `soft` sin rejilla. const soft = g.physics.areasAt(down, 'soft')[0] ?? g.physics.areasAt(fwd, 'soft')[0]; g.vfx.burst('dust', b.x + this.facing * 0.3, feet, { count: 4, dirX: this.facing }); if (soft) { g.vfx.burst('dust', b.x, feet, { count: 10, scale: 1.2, color: 0x9a6a3a }); g.gfx.cam.shake(0.1, 0.12); g.events.emit('hero:dig', { x: b.x, y: feet, area: soft }); } } // ───────── vida ───────── takeHit(hit: Hit): boolean { if (!this._alive || this.invuln > 0 || this.fallResetT > 0 || this.respawning) return false; if (hit.damage <= 0) return false; const g = this.game; const b = this.body; const st = g.state; st.data.hp = Math.max(0, st.data.hp - hit.damage); st.changed(); g.events.emit('hero:hurt', { hp: st.data.hp, damage: hit.damage }); const dir = hit.dirX || (hit.source ? (b.x < hit.source.x ? -1 : 1) : -this.facing); b.vx = dir * (hit.knock ?? T.hp.knock); b.vy = T.hp.knockY; this.hurtT = T.hp.stun; this.invuln = T.hp.invuln; this.cancelActions(); g.hitstop(T.hp.hitstop); g.gfx.cam.shake(T.hp.shake, 0.3); g.audio.sfx('hurt', { x: b.x }); g.vfx.burst('hit', b.x, b.y, { scale: 1.2, color: 0xff4040 }); g.vfx.burst('star', b.x, b.y + 0.4, { count: 3 }); this.rig.play('hurt'); this.rig.flash(0xff3030, 0.3); this.tempExpr('hurt', 0.6); if (st.data.hp <= 0) this.die(); return true; } heal(n: number): void { const st = this.game.state; const before = st.data.hp; st.data.hp = Math.min(st.data.maxHp, st.data.hp + n); st.changed(); if (st.data.hp > before) { this.game.vfx.burst('heart', this.x, this.y + 0.5, { count: 4 }); this.game.audio.sfx('heart'); this.rig.flash(0xff7fa0, 0.3); this.tempExpr('love', 0.8); } } private cancelActions(): void { this.attackT = 0; this.attackQueued = false; this.dashT = 0; this.breathT = 0; this.diving = false; this.digT = 0; } private die(): void { const g = this.game; this._alive = false; this.deadT = 0; this.cancelActions(); this.body.vx = -this.facing * 2; this.body.vy = 9; this.rig.play('defeat', { loop: true }); this.rig.setExpression('hurt', 0.1); g.audio.sfx('die'); g.gfx.cam.shake(0.5, 0.4); g.hitstop(0.15); g.events.emit('hero:died', {}); } private async respawn(): Promise { const g = this.game; this.respawning = true; try { await g.ui.fade(true, 0.35); const st = g.state; st.data.hp = st.data.maxHp; st.changed(); const { zone, spawn } = st.data; // Mismo nivel: basta con volver al punto de control (reconstruir el nivel era lo que tardaba). if (g.hasZone(zone) && g.zone?.id !== zone) { await g.loadZone(zone, spawn, false); } else if (g.zone) { const sp = g.zone.spawns[spawn] ?? g.zone.spawns.default; this.teleport(sp.x, sp.y); g.gfx.cam.snap(sp.x, sp.y); } this._alive = true; this.hiddenDeath = false; this.invuln = T.hp.respawnInvuln; this.hurtT = 0; this.rig.play('victory'); this.rig.setExpression(LOOKS[this._power].expr, 0); g.events.emit('hero:respawn', {}); } finally { this.respawning = false; } await g.ui.fade(false, 0.35); } private fallOut(kind: 'water' | 'pit' | 'lava', surface: number): void { const g = this.game; const b = this.body; if (kind === 'lava') { g.vfx.burst('fire', b.x, surface, { count: 16, scale: 1.3 }); g.vfx.burst('smoke', b.x, surface + 0.3, { count: 8 }); g.audio.sfx('fire', { x: b.x }); g.audio.sfx('hurt', { x: b.x }); } else if (kind === 'water') { g.vfx.burst('splash', b.x, surface, { count: 14, scale: 1.3 }); g.audio.sfx('splash', { x: b.x }); } else { g.audio.sfx('whoosh', { pitch: 0.6 }); } this.cancelActions(); b.vx = b.vy = 0; const st = g.state; st.data.hp = Math.max(0, st.data.hp - T.fall.damage); st.changed(); g.events.emit('hero:hurt', { hp: st.data.hp, damage: T.fall.damage }); if (st.data.hp <= 0) { this.die(); this.hiddenDeath = true; return; } this.fallResetT = T.fall.resetDelay; } private finishFallReset(): void { const g = this.game; this.teleport(this.lastSafe.x, this.lastSafe.y); this.invuln = T.hp.invuln; g.vfx.burst('poof', this.x, this.y, { count: 8 }); g.audio.sfx('teleport', { volume: 0.5 }); this.rig.squash(0.35); this.tempExpr('surprised', 0.5); } teleport(x: number, y: number): void { const b = this.body; this.setPos(x, y + T.body.hh); b.vx = b.vy = 0; b.ground = null; b.dropThrough = 0; this.lastSafe.x = x; this.lastSafe.y = y; this.wasGround = true; this.fallResetT = 0; this.cancelActions(); } // ───────── recompensas ───────── grantPower(p: PowerId): void { const g = this.game; g.state.addPower(p); g.events.emit('hero:grant', { kind: 'power', id: p }); const L = LOOKS[p]; void g.ui.reward({ kind: 'power', emoji: L.emoji, name: `¡Poder ${L.name}!`, desc: L.desc }); g.audio.sfx('powerup'); g.vfx.burst('confetti', this.x, this.y + 0.8, { count: 24 }); this.setPower(p); this.rig.play('victory'); } grantTool(t: ToolId): void { const g = this.game; g.state.addTool(t); autoAssignSlots(g.state); g.events.emit('hero:grant', { kind: 'tool', id: t }); const info = TOOLS[t]; void g.ui.reward({ kind: 'tool', emoji: info.emoji, name: info.name, desc: info.desc }); g.audio.sfx('powerup'); g.vfx.burst('confetti', this.x, this.y + 0.8, { count: 24 }); g.vfx.burst('emoji', this.x, this.y + 1, { emoji: info.emoji, count: 1 }); this.rig.play('victory'); this.tempExpr('happy', 1.4); } private tempExpr(e: Expression, secs: number): void { this.rig.setExpression(e, 0.1); this.exprT = secs; } // ───────── render ───────── render(alpha: number, dt: number): void { super.render(alpha, dt); const g = this.game; const b = this.body; if (this.fallResetT > 0 || this.hiddenDeath) this.view.visible = false; else if (!this._alive) this.view.visible = true; else this.view.visible = this.invuln <= 0 || Math.floor(this.invuln * 16) % 2 === 0; if (this._alive) this.rig.update(dt, { vx: b.vx, vy: b.vy, onGround: b.onGround, facing: this.facing }); else this.rig.update(dt); // Sombra de contacto const vy = this.view.position.y; const feet = vy - T.body.hh; const gy = g.physics.groundBelow(this.view.position.x, feet + 0.05, 8); if (gy === null) this.shadow.visible = false; else { const h = feet - gy; this.shadow.visible = true; this.shadow.position.set(0, gy - vy + 0.02, 0); const k = Math.max(0.35, 1 - h * 0.12); this.shadow.scale.setScalar(k); (this.shadow.material as THREE.MeshBasicMaterial).opacity = 0.38 * k; } } }