7. Finish the game loop
The last chapter makes it a game you can lose: enemies within reach bite, your health shows on the HUD line, a bite that takes the last of it ends the game, and a dialog starts it again.
// src/combat.ts
import * as THREE from 'three';
import type { FPS } from 'marble3';
import { GraphicEntity } from 'marble3/entity';
import { raycastFromCamera } from 'marble3/physics';
import type { Player } from 'marble3/player';
import { Enemy } from './enemy';
import { loadGun } from './gun';
const MAX_HP = 100;
const BITE = 8; // health one bite takes
const REACH = 2.2; // how close an enemy must be to bite
const BITE_COOLDOWN = 850; // ms between one enemy's bites
export class Combat extends GraphicEntity {
private enemies: Enemy[] = [];
private wave = 0;
private kills = 0;
private hp = MAX_HP;
private over = false;
private nextBite = new WeakMap<Enemy, number>();
constructor(private fps: FPS, private player: Player) {
super();
loadGun(player.camera);
document.addEventListener('mousedown', this.shoot);
this.nextWave();
}
private nextWave() {
this.wave++;
this.hp = MAX_HP;
for (let i = 0; i < 2 + this.wave; i++) this.spawn(this.spawnPoint());
this.show();
}
// A random spot on the floor, clear of the pillars and at least 18 units from the player.
private spawnPoint() {
const p = this.player.position;
for (;;) {
const x = (Math.random() - 0.5) * 90;
const z = (Math.random() - 0.5) * 90;
const nearPillar = Math.hypot(x - Math.round(x / 20) * 20, z - Math.round(z / 20) * 20) < 6;
if (!nearPillar && Math.hypot(x - p.x, z - p.z) > 18) return new THREE.Vector3(x, 3, z);
}
}
private spawn(at: THREE.Vector3) {
const enemy = new Enemy(this.player);
enemy.position = at;
this.fps.add(enemy);
this.enemies.push(enemy);
}
private show() {
this.fps.hud.text('status', `Wave ${this.wave} · ${this.enemies.length} left · ${this.kills} kills`, 'top');
this.fps.hud.text('status', `Wave ${this.wave} · ${this.enemies.length} left · ${this.kills} kills · ❤ ${this.hp}`, 'top');
}
private shoot = (e: MouseEvent) => {
if (e.button !== 0) return;
if (e.button !== 0 || this.over) return;
const { collision } = raycastFromCamera(this.player.camera, this.fps.world);
const hit = collision?.entityId ? this.fps.entities[collision.entityId] : undefined;
if (hit instanceof Enemy) hit.hit();
};
update() {
if (this.over) return;
// Bites: each enemy within reach takes BITE, at most once every BITE_COOLDOWN.
const now = performance.now();
const p = this.player.position;
for (const e of this.enemies) {
if (Math.hypot(e.position.x - p.x, e.position.z - p.z) > REACH) continue;
if (now < (this.nextBite.get(e) ?? 0)) continue;
this.nextBite.set(e, now + BITE_COOLDOWN);
this.hp = Math.max(0, this.hp - BITE);
this.show();
}
if (this.hp === 0) return this.lose();
const dead = this.enemies.filter((e) => e.dead);
if (!dead.length) return;
for (const e of dead) this.fps.remove(e);
this.kills += dead.length;
this.enemies = this.enemies.filter((e) => !e.dead);
// An empty arena brings the next wave.
if (this.enemies.length) this.show();
else this.nextWave();
}
private lose() {
this.over = true;
for (const e of this.enemies) this.fps.remove(e);
this.enemies = [];
document.exitPointerLock();
this.fps.hud.dialog({
title: 'You died',
lines: [`Wave ${this.wave}, ${this.kills} kills.`],
onClose: () => this.restart(),
});
}
private restart() {
this.fps.hud.dialog(null);
this.wave = 0;
this.kills = 0;
this.over = false;
this.nextWave();
}
dispose() {
document.removeEventListener('mousedown', this.shoot);
super.dispose();
}
}- Bites. An enemy stops 1.2 units from you (chapter 3), well inside
REACH, so whatever catches you bites. TheWeakMapkeeps each enemy's next allowed bite without a field on the enemy, and forgets an enemy once it is gone. Each new wave heals you back to 100. - Game over. At 0 the enemies leave, the mouse is released so you can use it, and
hud.dialogshows a card over the dimmed world: a title, a line, and a Got it button. Whileoveris set,updatestops andshootignores clicks, so the click that closes the card fires nothing. - Restart. Closing the dialog, by its button or by clicking the dimmed area, calls
onClose.restartremoves the dialog, zeroes the counts and callsnextWave, which heals you and sends wave 1 again.
What you should see: the top line now ends with ❤ 100. Let an enemy reach you and the number drops by 8 a bite, a little more than once a second, faster with several on you. Clear a wave and it is back to 100. Let it reach 0: the enemies vanish, the mouse is free, and a You died card says how far you got. Click Got it, then the canvas to take the mouse again: wave 1, three enemies, full health.
The finished game
Your src/ folder holds the whole game, each file as its chapter last left it:
| File | Last changed in |
|---|---|
main.ts, arena.ts | 1. Build the arena |
game.ts, gun.ts | 4. Shoot and detect hits |
enemy.ts, health-bar.ts | 5. Show enemy health |
combat.ts | this chapter |
Plus public/sci-fi-gun.glb and public/draco/ from chapter 4.
Where to go next
The Quick FPS preview is this game grown up. Each of its extras is a file or two in website/demos/quick-fps/ that you can bring over:
- Weapon switching. Three guns with their own damage and fire rate, F to cycle, hold to fire, and a muzzle flash (
weapon.ts); tracers and impact sparks (shot-effects.ts). - Enemy variants.
ENEMY_KINDSinenemy.tsturns the red walker into one row of a table: a pink brute and a green boss with more health, harder bites and a bigger bar. Flyers hover over you and drop a cage (flying-enemy.ts,cage.ts). - Touch controls.
hud.tsadds FIRE and switch buttons whenTOUCH_ENABLEDis true, andcombat.tslistens to them instead of the mouse; as built here, a tap to look around also fires. - A screen of its own. The same
hud.tsdraws a health bar, a hit marker, a damage vignette and a game-over overlay in place of the HUD line and dialog.
The other examples are complete games too, one folder each; the board scene shows the Game class this tutorial didn't use, and Mobile adds the rotate prompt and fullscreen button for phones.