/** * Base de los NPC: chibi con vida propia (idle, mirar al héroe, saludar, hablar), globito * ❗/💬 sobre la cabeza e interacción "[E] Hablar" → `ui.dialog` → evento `npc:talk {id}`. * * Las subclases implementan `script()` (líneas según flags + acción al terminar) y `hasNews()`. */ import * as THREE from 'three'; import { Entity } from '../../core/entity'; import type { DialogLine, Hit } from '../../core/types'; import { createChibi } from '../../characters/chibi'; import type { ChibiOptions, ChibiRig, Expression } from '../../characters/types'; import { blobShadow, emojiMesh, emojiSprite } from '../../render'; import { rand } from '../../core/math'; import type { Interactable } from './interact'; export interface NpcLook { /** Id lógico (`npc:talk {id}`). */ id: string; name: string; /** Retrato del diálogo. */ emoji: string; chibi: ChibiOptions; /** Emoji que sujeta en la mano (⛏️, 🍞…). */ held?: string; /** Hacia dónde mira por defecto. */ facing?: 1 | -1; } export interface Script { lines: DialogLine[]; /** Se ejecuta al cerrar el diálogo (flags, regalos, misiones). */ after?: () => void | Promise; } const BUBBLE_Y = 0.62; export abstract class Npc extends Entity implements Interactable { readonly npcId: string; readonly npcName: string; readonly portrait: string; readonly rig: ChibiRig; readonly size: number; readonly interactRange = { x: 1.7, y: 1.8 }; protected face: 1 | -1; protected baseExpr: Expression; protected talking = false; /** Tiempo desde que el héroe se acercó (para saludar una vez por visita). */ private near = false; private waveCd = 0; private hitCd = 0; private t = rand(0, 10); private idleT = rand(4, 8); private readonly shadow: THREE.Mesh; private readonly news: THREE.Sprite; private readonly chat: THREE.Sprite; private held: THREE.Mesh | null = null; private newsK = 0; private chatK = 0; constructor(look: NpcLook) { super(); this.npcId = look.id; this.npcName = look.name; this.portrait = look.emoji; this.size = look.chibi.size ?? 1; this.face = look.facing ?? -1; this.baseExpr = look.chibi.expression ?? 'smile'; this.team = 'neutral'; this.tags.add('npc'); this.rig = createChibi(look.chibi); this.rig.root.position.y = this.size * 0.5; this.view.add(this.rig.root); if (look.held) { const m = emojiMesh(look.held, 0.55 * this.size, { shadow: false }); m.position.set(0.52 * this.size, -0.05 * this.size, 0.35); m.rotation.z = -0.35; this.rig.root.add(m); this.held = m; } this.shadow = blobShadow(0.45 * this.size, 0.35); this.shadow.position.y = 0.02; this.view.add(this.shadow); this.news = emojiSprite('❗', 0.8, { glow: 0.4 }); this.chat = emojiSprite('💬', 0.55); for (const s of [this.news, this.chat]) { s.position.set(0.15, this.size + BUBBLE_Y, 0.3); s.scale.setScalar(0.001); s.renderOrder = 5; this.view.add(s); } } /** Diálogo actual según flags. */ protected abstract script(): Script; /** true = ❗ sobre la cabeza (tiene algo nuevo que decir). */ hasNews(): boolean { return false; } // ───────── helpers de guion ───────── protected say(...texts: string[]): DialogLine[] { return texts.map((text) => ({ speaker: this.npcName, emoji: this.portrait, text })); } protected hero(text: string): DialogLine { const p = this.game.hero?.power ?? 'base'; const emoji = { base: '🙂', fury: '😡', ice: '🥶', fire: '🔥', cool: '😎' }[p] ?? '🙂'; return { speaker: 'Tú', emoji, text }; } protected get flags() { return this.game.state; } // ───────── interacción ───────── interactText(): string | null { return this.talking ? null : 'Hablar'; } interactAnchor(): { x: number; y: number } { return { x: this.x, y: this.y + this.size + 1.25 }; } interact(): void { void this.talk(); } async talk(): Promise { if (this.talking) return; const g = this.game; const hero = g.hero; this.talking = true; if (hero) { hero.inputLocked = true; hero.facing = this.x >= hero.x ? 1 : -1; this.lookAt(hero.x); } const s = this.script(); this.rig.play('talk', { loop: true }); this.rig.squash(0.2); this.rig.setExpression(this.talkExpr(), 0.15); try { await g.ui.dialog(s.lines); } finally { this.rig.play('idle'); this.rig.setExpression(this.baseExpr, 0.2); if (hero) hero.inputLocked = false; this.talking = false; } g.events.emit('npc:talk', { id: this.npcId }); await s.after?.(); g.state.save(); } protected talkExpr(): Expression { return this.baseExpr === 'neutral' ? 'smile' : this.baseExpr; } protected lookAt(x: number): void { if (Math.abs(x - this.x) > 0.05) this.face = x > this.x ? 1 : -1; } /** Golpes del héroe: reacción cómica, sin daño. */ takeHit(hit: Hit): boolean { if (this.hitCd > 0 || this.talking) return false; this.hitCd = 0.8; const g = this.game; this.rig.play('hurt'); this.rig.flash(hit.element === 'water' ? 0x7fd4ff : 0xffffff, 0.2); this.rig.setExpression('surprised', 0.08); g.after(0.7, () => this.rig.setExpression(this.baseExpr, 0.2)); const msg = hit.element === 'water' ? '¡Eh, que me mojas!' : hit.element === 'fire' ? '¡Quema, quema!' : '¡Ay! ¡Que soy de los buenos!'; g.vfx.floatText(msg, this.x, this.y + this.size + 0.6, '#ffffff'); g.audio.sfx('bounce', { pitch: 1.4, volume: 0.5, x: this.x }); return false; } bounds() { return { x: this.x, y: this.y + this.size * 0.5, hw: 0.4 * this.size, hh: 0.5 * this.size }; } // ───────── vida ───────── update(dt: number): void { this.t += dt; this.waveCd = Math.max(0, this.waveCd - dt); this.hitCd = Math.max(0, this.hitCd - dt); const hero = this.game.hero; const dx = hero ? hero.x - this.x : 99; const dy = hero ? hero.y - this.y : 99; const close = hero !== null && Math.abs(dx) < 4.5 && Math.abs(dy) < 3; if (close && hero && !this.talking) this.lookAt(hero.x); if (close && !this.near && this.waveCd <= 0 && !this.talking) { this.rig.play('wave'); this.waveCd = 6; if (this.hasNews()) this.rig.squash(0.25); } this.near = close; // Pequeñas acciones de idle para que no parezca una estatua. if (!this.talking && !close) { this.idleT -= dt; if (this.idleT <= 0) { this.idleT = rand(5, 10); this.idleAction(); } } this.tick(dt, close); } /** Gancho por paso para las subclases. */ protected tick(_dt: number, _heroClose: boolean): void {} protected idleAction(): void { const r = Math.random(); if (r < 0.4) this.face = this.face === 1 ? -1 : 1; else if (r < 0.65) this.rig.play('victory', { speed: 1.3 }); else this.rig.squash(0.2); } /** Movimiento para el rig (las subclases que caminan lo sobrescriben). */ protected motionVx(): number { return 0; } render(alpha: number, dt: number): void { super.render(alpha, dt); this.rig.update(dt, { vx: this.motionVx(), vy: 0, onGround: true, facing: this.face }); // Globitos: ❗ con novedades; 💬 si el héroe está cerca y no hay novedades. const showNews = !this.talking && this.hasNews(); const showChat = !this.talking && !showNews && this.near; this.newsK += ((showNews ? 1 : 0) - this.newsK) * Math.min(1, dt * 10); this.chatK += ((showChat ? 1 : 0) - this.chatK) * Math.min(1, dt * 10); const tt = performance.now() / 1000 + this.id; const hop = Math.abs(Math.sin(tt * 3.2)) * 0.18; const pulse = 1 + Math.sin(tt * 6.4) * 0.06; this.news.scale.setScalar(Math.max(0.001, 0.8 * this.newsK * pulse)); this.news.position.y = this.size + BUBBLE_Y + hop; this.news.visible = this.newsK > 0.01; this.chat.scale.setScalar(Math.max(0.001, 0.5 * this.chatK)); this.chat.position.y = this.size + BUBBLE_Y + Math.sin(tt * 2) * 0.05; this.chat.visible = this.chatK > 0.01; } onRemoved(): void { if (this.talking && this.game.hero) this.game.hero.inputLocked = false; this.rig.dispose(); (this.held?.material as THREE.Material | undefined)?.dispose(); } }