LINE1 10 20 30 40 50 60 70 80 90 100 110 120 130 1401import * as THREE from 'three';2import { WEAPONS, ZOMBIES, AMMO, PRESTIGE } from './config.js';3import { state, save, recordKill, earnPoints } from './economy.js';4import { segmentSolidHit } from './city.js';5import { PARTS } from './zombies.js';6import * as audio from './audio.js';7import * as ui from './ui.js';8import * as settings from './settings.js';9import { icon } from './icons.js';10import { buildViewModel, animateViewModel } from './viewmodels.js';11import { Particles } from './particles.js';1213const G = 9.81;14const ZERO_RANGE = 150;15const BASE_SWAY = 0.0012;16const MAX_BULLET_LIFE = 6;1718export function weaponStats(id) {19 const w = WEAPONS[id];20 const m = state.mods[id] || {};21 const zoom = w.zoom.slice();22 if (m.scope) zoom[zoom.length - 1] += 2 * m.scope;23 const stock = Math.pow(0.8, m.stock || 0);24 return {25 id,26 name: w.name,27 ammo: w.ammo,28 damage: w.damage * (1 + 0.2 * (m.barrel || 0)),29 cooldown: w.cooldown * Math.pow(0.85, m.trigger || 0),30 mag: Math.ceil(w.mag * (1 + 0.25 * (m.mag || 0))),31 reload: w.reload * (state.upgrades.reloadBench ? 0.8 : 1),32 velocity: w.velocity,33 zoom,34 sway: w.sway * stock * (state.upgrades.tripod ? 0.85 : 1),35 spread: w.spread * stock,36 silent: w.silent,37 auto: !!w.auto,38 heavy: w.ammo === '50' || w.ammo === 'cell',39 rail: w.ammo === 'cell',40 bolt: w.action === 'bolt',41 ejects: w.ammo !== 'cell',42 color: w.color,43 length: w.length,44 };45}4647export function fovFor(zoom) {48 const t = Math.tan((settings.get('fov') * Math.PI) / 360) / zoom;49 return (2 * Math.atan(t) * 180) / Math.PI;50}5152const bulletGeo = new THREE.BoxGeometry(0.03, 0.03, 0.45);53const bulletMat = new THREE.MeshBasicMaterial({ color: 0xffe39a });5455const rand = (a, b) => a + Math.random() * (b - a);56const randInt = (a, b) => Math.floor(rand(a, b + 1));57const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];5859const WALL_DUST = [0xb3a58a, 0xa39a86, 0x9a8f7c];60const GROUND_DUST = 0x6e6250;61const CONCRETE_CHIP = [0x8f8576, 0x6f6a63, 0xb9b2a2];6263export class Combat {64 constructor(scene, camera, player, zombies) {65 this.scene = scene;66 this.camera = camera;67 this.player = player;68 this.zombies = zombies;69 this.bullets = [];70 this.particles = new Particles(scene);71 this.boltT = 0;72 this.loaded = {};73 this.reloadT = 0;74 this.cd = 0;75 this.scoped = false;76 this.zoomIdx = 0;77 this.zoom = 1;78 this.recoil = 0;79 this.headStreak = 0;80 this.breath = 0;81 this.breathing = false;82 this.t = 0;83 this.sway = { yaw: 0, pitch: 0 };84 this.vm = null;85 this.current = state.owned[state.equipped] ? state.equipped : 'hunter';86 this.refresh();87 this.equip(this.current, true);88 }8990 get stats() {91 return this._stats;92 }9394 refresh() {95 this._stats = weaponStats(this.current);96 this.breathMax = 4 + (state.upgrades.tripod ? 3 : 0);97 if (this.loaded[this.current] === undefined) this.loaded[this.current] = this._stats.mag;98 this.loaded[this.current] = Math.min(this.loaded[this.current], this._stats.mag);99 }100101 refreshAll() {102 for (const id of Object.keys(WEAPONS)) {103 if (id === this.current) continue;104 if (this.loaded[id] !== undefined) this.loaded[id] = Math.min(this.loaded[id], weaponStats(id).mag);105 }106 this.refresh();107 this.setViewModel();108 }109110 equip(id, silent = false) {111 if (!state.owned[id]) return false;112 if (this.current !== id || silent) {113 this.current = id;114 this.reloadT = 0;115 this.scoped = false;116 this.zoomIdx = 0;117 this.refresh();118 this.setViewModel();119 state.equipped = id;120 save();121 if (!silent) ui.notify(`Equipped ${this._stats.name}`);122 }123 return true;124 }125126 setViewModel() {127 if (this.vm) this.camera.remove(this.vm.group);128 this.vm = buildViewModel(this.current);129 this.camera.add(this.vm.group);130 }131132 toggleScope() {133 if (this.scoped) {134 this.scoped = false;135 return;136 }137 this.scoped = true;138 this.zoomIdx = 0;139 }140141 cycleZoom(dir) {142 if (!this.scoped) return;143 const n = this._stats.zoom.length;144 this.zoomIdx = (this.zoomIdx + (dir > 0 ? 1 : -1) + n) % n;145 }146147 sensMult() {148 return this.zoom > 1 ? 1 / Math.pow(this.zoom, 0.7) : 1;149 }150151 reload() {152 const s = this._stats;153 if (this.reloadT > 0 || this.loaded[this.current] >= s.mag) return;154 if (!state.ammo[s.ammo]) {155 ui.notify(`No ${AMMO[s.ammo].name} ammo. Craft some at the workbench.`, 'warn');156 audio.empty();157 return;158 }159 this.reloadT = s.reload;160 this.reloadTotal = s.reload;161 audio.reload();162 }163164 finishReload() {165 const s = this._stats;166 const need = s.mag - this.loaded[this.current];167 const take = Math.min(need, state.ammo[s.ammo]);168 this.loaded[this.current] += take;169 state.ammo[s.ammo] -= take;170 if (take > 0) audio.magIn();171 save();172 }173174 fire() {175 const s = this._stats;176 if (this.reloadT > 0 || this.cd > 0) return false;177 if (this.loaded[this.current] <= 0) {178 if (state.ammo[s.ammo] > 0) this.reload();179 else {180 audio.empty();181 ui.notify(`Out of ${AMMO[s.ammo].name} ammo`, 'warn');182 this.cd = 0.3;183 }184 return false;185 }186 this.loaded[this.current]--;187 this.cd = s.cooldown;188 this.vm.shotT = 0;189 state.stats.shots++;190191 const hipMult = this.scoped ? 1 : 2.5;192 const rx = rand(-1, 1) * s.spread * hipMult;193 const ry = rand(-1, 1) * s.spread * hipMult;194 const lift = (0.5 * G * ZERO_RANGE) / (s.velocity * s.velocity);195 const yaw = this.player.yaw + this.sway.yaw + rx;196 const pitch = this.player.pitch + this.recoil + this.sway.pitch + ry + lift;197 const dir = forward(yaw, pitch);198 this.recoil = Math.min(0.08, this.recoil + 0.012 * Math.min(1, s.damage / 150) + 0.003);199 const v = dir.multiplyScalar(s.velocity);200 const origin = new THREE.Vector3(this.player.x, this.player.viewFeet + this.player.eye, this.player.z);201 const mesh = new THREE.Mesh(bulletGeo, bulletMat);202 mesh.position.copy(origin);203 this.scene.add(mesh);204 this.bullets.push({ p: origin.clone(), origin, v, mesh, life: 0, damage: s.damage });205206 if (s.ejects) this.ejectCasing();207 if (s.bolt) this.boltT = s.cooldown * 0.45;208209 audio.shot({ silent: s.silent, heavy: s.heavy, rail: s.rail });210 if (!s.silent) this.zombies.alertAt(this.player.x, this.player.z, 220);211 return true;212 }213214 215 ejectCasing() {216 const yaw = this.player.yaw;217 const right = new THREE.Vector3(Math.cos(yaw), 0, -Math.sin(yaw));218 const pos = new THREE.Vector3(this.player.x, this.player.viewFeet + this.player.eye - 0.06, this.player.z).addScaledVector(right, 0.18);219 const v = right.multiplyScalar(rand(1.2, 1.9));220 v.y += rand(0.9, 1.5);221 v.x += rand(-0.2, 0.2);222 v.z += rand(-0.2, 0.2);223 this.particles.casing(pos, v);224 audio.casing(rand(0.25, 0.45));225 }226227 update(dt, { holding, fireHeld, playing, moving, sprinting }) {228 const s = this._stats;229 this.t += dt;230 this.cd = Math.max(0, this.cd - dt);231 if (this.reloadT > 0) {232 this.reloadT -= dt;233 if (this.reloadT <= 0) {234 this.reloadT = 0;235 this.finishReload();236 }237 }238239 this.breathing = playing && holding && this.scoped && this.breath > 0;240 if (this.breathing) this.breath = Math.max(0, this.breath - dt);241 else this.breath = Math.min(this.breathMax, this.breath + dt * 0.8);242243 if (this.boltT > 0) {244 this.boltT -= dt;245 if (this.boltT <= 0) {246 this.boltT = 0;247 audio.bolt(0);248 }249 }250251 if (playing && fireHeld && s.auto) this.fire();252253 const moveMult = sprinting ? 3 : moving ? 1.6 : 1;254 const amp = s.sway * BASE_SWAY * (this.scoped ? 1 : 2.5) * (this.breathing ? 0.25 : 1) * moveMult;255 const t = this.t;256 this.sway.yaw = amp * (Math.sin(t * 0.7) * 0.6 + Math.sin(t * 1.9 + 1.3) * 0.3 + Math.sin(t * 4.3) * 0.1);257 this.sway.pitch = amp * (Math.sin(t * 0.9 + 2) * 0.6 + Math.sin(t * 2.7) * 0.3 + Math.sin(t * 5.7 + 0.5) * 0.12);258 this.recoil *= Math.exp(-dt * 9);259260 this.zoom = this.scoped ? s.zoom[this.zoomIdx] : 1;261 const fov = this.zoom > 1 ? fovFor(this.zoom) : settings.get('fov');262 if (Math.abs(this.camera.fov - fov) > 0.01) {263 this.camera.fov = fov;264 this.camera.updateProjectionMatrix();265 }266 const reloadProgress = this.reloadT > 0 ? 1 - this.reloadT / this.reloadTotal : 0;267 animateViewModel(this.vm, dt, { recoil: this.recoil, reloadProgress, scoped: this.scoped, sprinting });268 this.player.applyCamera(this.recoil + this.sway.pitch, this.sway.yaw);269270 this.updateBullets(dt);271 this.particles.update(dt);272 }273274 updateBullets(dt) {275 for (let i = this.bullets.length - 1; i >= 0; i--) {276 const b = this.bullets[i];277 b.life += dt;278 b.v.y -= G * dt;279 const d = b.v.clone().multiplyScalar(dt);280 const p1 = b.p.clone().add(d);281282 let best = Infinity;283 let hit = null;284 const st = segmentSolidHit(b.p, p1);285 if (st <= 1 && st < best) {286 best = st;287 hit = { kind: 'solid' };288 }289 const zh = this.zombies.segmentHit(b.p, d);290 if (zh.z && zh.t <= 1 && zh.t < best) {291 best = zh.t;292 hit = { kind: 'zombie', z: zh.z, part: zh.part };293 }294 if (p1.y < 0) {295 const tg = b.p.y / (b.p.y - p1.y);296 if (tg >= 0 && tg <= 1 && tg < best) {297 best = tg;298 hit = { kind: 'ground' };299 }300 }301302 if (hit) {303 const hp = b.p.clone().addScaledVector(d, best);304 this.onImpact(b, hit, hp);305 this.scene.remove(b.mesh);306 this.bullets.splice(i, 1);307 continue;308 }309310 b.p.copy(p1);311 b.mesh.position.copy(b.p);312 b.mesh.lookAt(b.p.x + b.v.x, b.p.y + b.v.y, b.p.z + b.v.z);313 if (b.life > MAX_BULLET_LIFE) {314 this.scene.remove(b.mesh);315 this.bullets.splice(i, 1);316 }317 }318 }319320 321 countHeadshot() {322 this.headStreak += 1;323 if (this.headStreak < PRESTIGE.streak) return;324 this.headStreak = 0;325 earnPoints(PRESTIGE.streakPoints);326 ui.notify(`${PRESTIGE.streak} headshots in a row: +${PRESTIGE.streakPoints} prestige point`, 'ok');327 }328329 onImpact(b, hit, hp) {330 const travel = b.v.clone().normalize();331 if (hit.kind === 'ground') {332 this.headStreak = 0;333 this.particles.puff(hp, GROUND_DUST, { count: 4, size: 0.16, life: 0.9, spread: 0.6 });334 audio.impact();335 return;336 }337 if (hit.kind === 'solid') {338 this.headStreak = 0;339 340 const back = travel.clone().negate();341 this.particles.puff(hp, pick(WALL_DUST), { count: 3, size: 0.1, life: 0.7, spread: 0.5 });342 this.particles.debris(hp, back, pick(CONCRETE_CHIP), { count: 4, speed: 1.8 });343 audio.impact();344 return;345 }346 const z = hit.z;347 const head = hit.part === 'head';348 if (head) this.countHeadshot();349 else this.headStreak = 0;350 const mult = PARTS[hit.part].mult;351 z.hp -= b.damage * mult;352 const dist = b.origin.distanceTo(hp);353 this.particles.spray(hp, travel, { count: head ? 16 : 10, speed: head ? 2.8 : 2.2 });354 audio.thud();355356 if (z.hp > 0) {357 this.zombies.flinch(z, this.player.x, this.player.z, 8);358 this.zombies.hit(z, hit.part);359 ui.hitMarker(false);360 return;361 }362 this.zombies.kill(z, travel.x, travel.z);363 audio.kill();364 if (Math.random() < 0.6) audio.deathMoan();365 ui.hitMarker(true);366 const def = ZOMBIES[z.type];367 const reward = Math.round(randInt(def.money[0], def.money[1]) * (1 + dist / 250) * (head ? 2 : 1));368 state.money += reward;369 state.stats.earned += reward;370 recordKill(z.type, head, dist);371 if (Math.random() < PRESTIGE.luckyChance) {372 earnPoints(PRESTIGE.luckyPoints);373 ui.notify(`Lucky find: +${PRESTIGE.luckyPoints} prestige point`, 'ok');374 }375 const gains = [];376 for (const [res, [lo, hi]] of Object.entries(def.drops)) {377 const n = randInt(lo, hi);378 if (n > 0) {379 state.resources[res] = (state.resources[res] || 0) + n;380 gains.push(`<span class="gain">+${n} ${icon(res)}</span>`);381 }382 }383 save();384 const flavor = pick(def.lines);385 ui.killText(`${def.name} · ${Math.round(dist)} m · +$${reward}${head ? ' HEADSHOT' : ''}`, head, flavor);386 if (gains.length) ui.notify(gains.join(' '), '', true);387 }388}389390function forward(yaw, pitch) {391 return new THREE.Vector3(-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch));392}