xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / web / js / combat.js 192 lines7.1 kB Raw
1import * as THREE from '../vendor/three.module.js';
2import { part } from './props.js';
3import { createMini, flash } from './minis.js';
4import { maxHp } from './stats.js';
5import { T } from './theme.js';
6import { track } from './debug.js';
7import { applyEvent } from './playback.js';
8import { abilityName } from './abilities.js';
9
10const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
11const RANGE = 2.4;
12const SPREAD = 1.7;
13
14export function createCombat(scene, party, cam, ui, sound) {
15  const anims = [];
16  const bars = [];
17  let enemies = [];
18  let fast = false;
19  const hp = new Map();
20
21  const tween = (dur, fn) => anims.push({ t: 0, dur, fn });
22
23  function makeBar(fig, height) {
24    const g = new THREE.Group();
25    const back = part(g, 'box', T.bg, [0, 0, 0], [0.8, 0.1, 0.04]);
26    const fill = part(g, 'box', T.danger, [0, 0, 0.03], [0.76, 0.07, 0.04]);
27    g.position.y = height;
28    fig.add(g);
29    bars.push(g);
30    return { g, fill, back };
31  }
32
33  function setBar(bar, ratio) {
34    const r = Math.max(0, ratio);
35    bar.fill.scale.x = 0.76 * r;
36    bar.fill.position.x = -0.38 * (1 - r);
37  }
38
39  function spawnEnemies(encounter, dir) {
40    const base = party.pos;
41    const across = new THREE.Vector3(-dir.z, 0, dir.x);
42    const n = encounter.enemies.length;
43    return encounter.enemies.map((e, i) => {
44      const big = encounter.boss && i === 0;
45      const fig = createMini(e, { enemy: true, boss: big });
46      const size = fig.userData.size;
47      const side = encounter.boss ? (i % 2 ? 1 : -1) * (0.95 + Math.floor((i - 1) / 2) * 0.7) : (i - (n - 1) / 2) * 0.7;
48      const depth = big ? RANGE + 0.5 : RANGE + (encounter.boss ? 0 : (i % 2) * 0.35);
49      fig.position.copy(base).addScaledVector(dir, depth).addScaledVector(across, big ? 0 : side);
50      fig.rotation.y = Math.atan2(-dir.x, -dir.z);
51      fig.scale.setScalar(0.01);
52      tween(0.35, (p) => fig.scale.setScalar(size * Math.max(0.01, p)));
53      scene.add(fig);
54      const bar = makeBar(fig, 1.3);
55      return { unit: e, fig, bar, hp: e.stats.hp, max: e.stats.maxHp, home: fig.position.clone() };
56    });
57  }
58
59  function lunge(fig, toward, dur) {
60    const home = fig.position.clone();
61    const dir = toward.clone().sub(home).setY(0).normalize().multiplyScalar(0.7);
62    tween(dur, (p) => fig.position.copy(home).addScaledVector(dir, Math.sin(p * Math.PI)));
63  }
64
65  function squash(fig) {
66    const body = fig.userData.body;
67    tween(0.18, (p) => body.scale.set(1 + Math.sin(p * Math.PI) * 0.18, 1 - Math.sin(p * Math.PI) * 0.22, 1 + Math.sin(p * Math.PI) * 0.18));
68  }
69
70  function strike(ev, t, heal) {
71    const next = applyEvent(hp, ev, t.max);
72    if (!t.ally) setBar(t.bar, next / t.max);
73    if (!heal && ev.amount > 0) {
74      flash(t.fig);
75      squash(t.fig);
76      sound.play(ev.crit ? 'crit' : 'hit');
77      if (ev.crit) cam.shake(0.5);
78    } else if (heal) {
79      flash(t.fig, T.heal);
80      sound.play('heal');
81    }
82    const [sx, sy] = cam.screenOf(t.fig);
83    ui.floater(sx, sy, heal ? `+${ev.amount}` : ev.dodged ? 'Dodge' : `${ev.amount}${ev.crit ? '!' : ''}`, heal ? 'heal' : ev.dodged ? 'gain' : ev.crit ? 'crit' : t.ally ? 'hurt' : 'dmg');
84    if (ev.killed) {
85      sound.play('fall');
86      cam.shake(0.35);
87      const f = t.fig;
88      if (t.ally) {
89        const body = f.userData.body;
90        party.topple(f, true);
91        const end = body.rotation.z;
92        tween(0.4, (p) => (body.rotation.z = end * p));
93      }
94      else tween(0.5, (p) => (f.scale.setScalar(Math.max(0.01, (1 - p) * f.userData.size)), (f.position.y = t.home.y - p * 0.3)));
95    }
96  }
97
98  function effect(ev, t) {
99    flash(t.fig, T.accent);
100    sound.play('heal');
101    const [sx, sy] = cam.screenOf(t.fig);
102    ui.floater(sx, sy, abilityName(ev.ability), 'gain');
103  }
104
105  async function play(state, before, at) {
106    const enc = state.encounter;
107    const log = state.log || [];
108    const poi = state.map.pois.find((q) => q.id === enc.poi);
109    ui.setCombat(true, enc.boss ? `Boss fight at ${poi.name}` : poi ? `Fight at ${poi.name}` : `Fight: ${enc.enemies[0].name}`);
110    const dir = at.clone().sub(party.pos).setY(0);
111    if (dir.lengthSq() < 1e-4) dir.set(1, 0, 0);
112    dir.normalize();
113    party.face(Math.atan2(dir.x, dir.z), true);
114    party.widen(SPREAD);
115    const foes = spawnEnemies(enc, dir);
116    enemies = foes;
117    const ids = new Map();
118    hp.clear();
119    foes.forEach((f) => {
120      ids.set(f.unit.id, f);
121      hp.set(f.unit.id, f.hp);
122    });
123    const prev = Object.fromEntries(before.party.units.map((u) => [u.id, u]));
124    state.party.units.forEach((u) => {
125      const fig = party.figures.get(u.id);
126      const p = prev[u.id] || u;
127      ids.set(u.id, { unit: u, fig, ally: true, max: maxHp(p) });
128      hp.set(u.id, p.stats.hp);
129    });
130    for (const f of party.figures.values()) f.userData.mode = 'idle';
131    const mid = party.pos.clone().addScaledVector(dir, RANGE / 2);
132    cam.setFocus(mid, 10);
133    ui.render(before, hp);
134    ui.logLine(`${enc.boss ? 'Boss fight' : 'Fight'}: ${foes.map((f) => f.unit.name).join(', ')}`, 'head');
135    ui.logLine('Space or a click speeds up the fight.', 'hint');
136    fast = false;
137    await sleep(700);
138
139    const base = THREE.MathUtils.clamp(24000 / Math.max(log.length, 1), 450, 800);
140    for (const ev of log) {
141      const turn = fast ? 220 : base;
142      const a = ids.get(ev.actor);
143      const t = ids.get(ev.target);
144      const heal = ev.kind === 'heal';
145      const cast = heal || ev.kind === 'buff' || ev.kind === 'debuff';
146      if (a) {
147        a.fig.userData.mode = cast ? 'cast' : 'fight';
148        a.fig.userData.swing?.();
149        if (t && a !== t && !cast) lunge(a.fig, t.fig.position, (turn / 1000) * 0.9);
150      }
151      await sleep(turn * 0.45);
152      if (t && cast && !heal) effect(ev, t);
153      else if (t) strike(ev, t, heal);
154      ui.logLine(ev.text, ev.killed ? 'kill' : ev.crit ? 'crit' : '');
155      ui.render(before, hp);
156      await sleep(turn * 0.55);
157      if (a) a.fig.userData.mode = 'idle';
158    }
159    await sleep(500);
160    track.drift = drift(state, before, foes);
161    for (const f of party.figures.values()) f.userData.mode = null;
162    party.sync(state.party.units);
163    party.widen(1);
164    for (const f of foes) scene.remove(f.fig);
165    bars.length = 0;
166    enemies = [];
167    cam.setFocus(null);
168    ui.setCombat(false);
169  }
170
171  function drift(state, before, foes) {
172    const out = [];
173    const was = Object.fromEntries(before.party.units.map((u) => [u.id, u.level]));
174    for (const u of state.party.units) if (was[u.id] === u.level && hp.get(u.id) !== u.stats.hp) out.push(`${u.name} shown ${hp.get(u.id)} hp, server ${u.stats.hp}`);
175    if (state.rewards) for (const f of foes) if (hp.get(f.unit.id) !== 0) out.push(`${f.unit.name} shown ${hp.get(f.unit.id)} hp after a won fight`);
176    return out;
177  }
178
179  function update(dt) {
180    for (const e of enemies) e.fig.userData.animate(e.fig.userData.mode || 'idle', dt);
181    for (let i = anims.length - 1; i >= 0; i--) {
182      const a = anims[i];
183      a.t += dt;
184      const p = Math.min(1, a.t / a.dur);
185      a.fn(p);
186      if (p >= 1) anims.splice(i, 1);
187    }
188    for (const b of bars) b.quaternion.copy(b.parent.quaternion).invert().multiply(cam.camera.quaternion);
189  }
190
191  return { play, update, hurry: () => (fast = true) };
192}