Skip to content

4. Shoot and detect hits ​

A gun in your hand, a shot that goes where the crosshair is, and an enemy that dies after three hits.

A gun ​

The model is the example's “Sci-fi Gun” by Harry_L, licensed under CC BY 4.0: you may ship it, crediting its author. Copy two things into your app's public/ folder:

  • sci-fi-gun.glb from the example's assets/guns/;
  • node_modules/three/examples/jsm/libs/draco/, as public/draco/: the model's geometry is Draco-compressed, and this is three.js's decoder for it.
ts
// src/gun.ts
import * as THREE from 'three';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const loader = new GLTFLoader().setDRACOLoader(new DRACOLoader().setDecoderPath('/draco/'));

// "Sci-fi Gun" by Harry_L (sketchfab.com/3d-models/sci-fi-gun-53b158b0d5a54b4491b09d1fb3058e29), CC BY 4.0.
export const loadGun = async (camera: THREE.Camera) => {
  const gltf = await loader.loadAsync('/sci-fi-gun.glb');
  const meshes: THREE.Mesh[] = [];
  gltf.scene.traverse((o) => {
    if ((o as THREE.Mesh).isMesh) meshes.push(o as THREE.Mesh);
  });
  const gun = new THREE.Group();
  for (const mesh of meshes) {
    mesh.rotateY(-Math.PI / 2);
    mesh.rotateZ(-Math.PI / 20);
    mesh.scale.setScalar(0.001);
    mesh.position.set(0.5, -0.5, -0.75);
    gun.add(mesh);
  }
  camera.add(gun); // a child of the camera: it follows your view, and has no body to block a shot
};

The gun is a child of the camera, not an entity: it has no body, so it never stands between you and what you shoot at.

An enemy that can be hit ​

Give the enemy three hit points, and a flash when one lands:

ts
// src/enemy.ts
import * as THREE from 'three';
import type { FPS } from 'marble3';
import * as bullet from 'marble3/bullet';
import { CharacterEntity } from 'marble3/entity';
import type { Player } from 'marble3/player';

export class Enemy extends CharacterEntity {
  hp = 3; 
  private dir = new THREE.Vector3();

  constructor(private target: Player) {
    super({
      shape: new bullet.btSphereShape(0.8),
      geometry: new THREE.IcosahedronGeometry(0.8),
      material: new THREE.MeshStandardMaterial({ color: 0xff3030, emissive: 0xaa0000, emissiveIntensity: 0.35, flatShading: true }),
      mass: 4,
      walkSpeed: 3.5, // slower than the player's 6, so you can outrun it
    });
  }

  get dead() { 
    return this.hp <= 0; 
  } 
  hit() { 
    this.hp -= 1; 
    const material = this.mesh?.material as THREE.MeshStandardMaterial; 
    material.emissiveIntensity = 0.85; 
    setTimeout(() => (material.emissiveIntensity = 0.35), 60); 
  } 
  update(delta = 0, engine?: FPS) {
    const p = this.target.position;
    const me = this.position;
    const dx = p.x - me.x;
    const dz = p.z - me.z;
    const d = Math.hypot(dx, dz);
    this.controller.setWalkDirection(d > 1.2 ? this.dir.set(dx / d, 0, dz / d) : this.dir.set(0, 0, 0));
    super.update(delta, engine);
  }
}

The enemy doesn't remove itself when it dies: whoever keeps the list of enemies does, so the list and the world never disagree.

Combat ​

One entity runs the fight. It has no body or mesh of its own; fps.add gives it an update() every frame and its dispose() on the way out. For now it holds the gun, owns the one enemy and listens for clicks:

ts
// 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';

export class Combat extends GraphicEntity {
  private enemies: Enemy[] = [];

  constructor(private fps: FPS, private player: Player) {
    super();
    loadGun(player.camera);
    document.addEventListener('mousedown', this.shoot);
    this.spawn(new THREE.Vector3(10, 3, -30));
  }

  private spawn(at: THREE.Vector3) {
    const enemy = new Enemy(this.player);
    enemy.position = at;
    this.fps.add(enemy);
    this.enemies.push(enemy);
  }

  private shoot = (e: MouseEvent) => {
    if (e.button !== 0) 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() {
    // The dead leave the world here, once their last hit has landed.
    for (const e of this.enemies) if (e.dead) this.fps.remove(e);
    this.enemies = this.enemies.filter((e) => !e.dead);
  }

  dispose() {
    document.removeEventListener('mousedown', this.shoot);
    super.dispose();
  }
}

A shot is raycastFromCamera: a Bullet ray from the middle of the screen, along the view. It returns the closest body it hits, with the id of the entity that body belongs to, and fps.entities turns the id back into the entity. A pillar or the floor comes back too; the instanceof Enemy check is what makes those misses.

createGame hands the enemy to Combat: the three lines of chapter 3 move into its spawn.

ts
// src/game.ts
import * as THREE from 'three';
import { FPS } from 'marble3';
import { LookAtCursor } from 'marble3/cursor';
import { defaultLights } from 'marble3/lights';
import { Player } from 'marble3/player';

import { buildArena, sunset } from './arena';
import { Enemy } from './enemy'; 
import { Combat } from './combat'; 

export const createGame = (): HTMLElement => {
  const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 0.1, 4000);
  const fps = new FPS();

  fps.scene.add(defaultLights());
  fps.scene.add(sunset());
  fps.renderer.toneMapping = THREE.ACESFilmicToneMapping; // the sky is in physical units
  fps.renderer.toneMappingExposure = 0.6;
  buildArena(fps);

  const player = new Player({ camera });
  player.position = new THREE.Vector3(0, 0, 0);
  fps.add(player);

  const el = fps.start(player);
  fps.add(new LookAtCursor(player));
  fps.add(new Combat(fps, player)); 
  const enemy = new Enemy(player); 
  enemy.position = new THREE.Vector3(10, 3, -30); 
  fps.add(enemy); 
  return el;
};

What you should see: the gun sits at the bottom right of your view and turns with it. The enemy comes for you as before. Put the crosshair on it and click: it flashes bright red. The third hit removes it. A click on a pillar, the floor or the sky does nothing.

The full example fires on hold as well as click, with a rate per gun, and draws a tracer and a spark where each shot lands (combat.ts, shot-effects.ts). Three hits are hard to count by flashes alone; chapter 5 puts a health bar over the enemy.