# BVH Mesh & Character Capsule Collision in Three.js

> Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.

- **Canonical page:** https://gamecrew.ai/techniques/three/bvh-character-capsule-collision
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** physics
- **Tags:** `collision`, `bvh`, `capsule`, `physics`, `mesh`, `slopes`, `spatial-hash`, `threejs`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Axis-aligned box colliders alone make sculptural bridges, curved ramps, rocky islets, and imported environment glTFs feel stiff or leaky. Pairing the studio's `CollisionWorld` (`addMesh`) or a custom `MeshBVH` triangle accelerator with a swept capsule keeps movement smooth at 60 Hz:

1. **Compute Local Capsule Bounds Once Per Step**: Transform the character's vertical segment $[A, B]$ into the collider mesh's inverse world matrix using pre-allocated module-scope scratch objects (`THREE.Vector3`, `THREE.Line3`, `THREE.Box3`, `THREE.Matrix4`). Never `new` math or geometry objects inside `game.onUpdate`.
2. **Accumulate Contacts Over `shapecast`**: Let `bvh.shapecast` visit only bounding boxes overlapping the inflated capsule AABB, clamp the segment vs triangle closest point (`tri.closestPointToPoint` + segment projection), and push the capsule segment out iteratively.
3. **Separate Slope Walkability from Wall Pushout**: Classify any floor contact whose normal satisfies $n_y \ge \cos(\theta_{\max})$ (default `45°`, $n_y \ge 0.707$) as walkable ground and zero downward velocity; project wall contacts along $\hat{\mathbf{n}}$ so running diagonally into curved walls slides smoothly without snagging.

## Mathematical & Algorithmic Core

- **Capsule Penetration Vector**: For segment point $\mathbf{p}_s$ and closest triangle point $\mathbf{p}_t$ with distance $d = \|\mathbf{p}_s - \mathbf{p}_t\| < r$:
  $$\Delta \mathbf{p} = \frac{\mathbf{p}_s - \mathbf{p}_t}{\max(d, 10^{-5})} \cdot (r - d)$$
- **Wall Sliding**: Remove only the inward velocity component along horizontal wall normal $\hat{\mathbf{n}}$ when $\mathbf{v} \cdot \hat{\mathbf{n}} < 0$:
  $$\mathbf{v}' = \mathbf{v} - (\mathbf{v} \cdot \hat{\mathbf{n}})\hat{\mathbf{n}}$$

## Engine Implementation

### Zero-Allocation `MeshBVH` Capsule Sweep Solver (`Assets/Game/bvh-capsule.ts`)

```ts
import * as THREE from 'three';
import { MeshBVH, StaticGeometryGenerator } from 'three-mesh-bvh';
import { CollisionWorld, type Game } from 'ccgd';

export interface BvhColliderSurface {
  readonly bvh: MeshBVH;
  readonly mesh: THREE.Mesh;
  readonly invMatrix: THREE.Matrix4;
  readonly matrixWorld: THREE.Matrix4;
}

export interface CapsuleBody {
  readonly basePos: THREE.Vector3;
  readonly velocity: THREE.Vector3;
  readonly radius: number;
  readonly height: number;
  grounded: boolean;
}

const _invMat = new THREE.Matrix4();
const _seg = new THREE.Line3();
const _box = new THREE.Box3();
const _tempBox = new THREE.Box3();
const _triPoint = new THREE.Vector3();
const _capsPoint = new THREE.Vector3();
const _delta = new THREE.Vector3();
const _worldNormal = new THREE.Vector3();
const _offset = new THREE.Vector3();
const _origin = new THREE.Vector3();
const _dir = new THREE.Vector3();

const MIN_FLOOR_NORMAL_Y = 0.707; // cos(45 deg)

export function bakeStaticBvh(root: THREE.Object3D): BvhColliderSurface {
  root.updateWorldMatrix(true, true);
  const generator = new StaticGeometryGenerator([root]);
  const merged = generator.generate();
  const bvh = new MeshBVH(merged);
  const mesh = new THREE.Mesh(merged);
  mesh.updateMatrixWorld(true);
  return {
    bvh,
    mesh,
    invMatrix: mesh.matrixWorld.clone().invert(),
    matrixWorld: mesh.matrixWorld,
  };
}

export function attachStudioMeshCollision(world: CollisionWorld, terrainRoot: THREE.Object3D): void {
  // Built-in kit shortcut for box + BVH terrain in one CollisionWorld:
  world.addMesh(terrainRoot, 'terrain');
}

export function resolveBvhCapsule(body: CapsuleBody, surface: BvhColliderSurface): void {
  surface.mesh.updateMatrixWorld(true);
  _invMat.copy(surface.matrixWorld).invert();

  const radius = body.radius;
  const halfShaft = Math.max(0.05, body.height * 0.5 - radius);

  // Build world-space segment inside the capsule shaft, then bring into BVH local space.
  _seg.start.set(body.basePos.x, body.basePos.y + radius, body.basePos.z);
  _seg.end.set(body.basePos.x, body.basePos.y + radius + halfShaft * 2, body.basePos.z);
  _seg.start.applyMatrix4(_invMat);
  _seg.end.applyMatrix4(_invMat);

  _box.makeEmpty();
  _box.expandByPoint(_seg.start);
  _box.expandByPoint(_seg.end);
  _box.min.addScalar(-radius);
  _box.max.addScalar(radius);

  body.grounded = false;

  surface.bvh.shapecast({
    intersectsBounds: (nodeBox) => nodeBox.intersectsBox(_box),
    intersectsTriangle: (tri) => {
      const dist = tri.closestPointToSegment(_seg, _triPoint, _capsPoint);
      if (dist >= radius) return false;

      _delta.subVectors(_capsPoint, _triPoint);
      const len = _delta.length();
      if (len < 1e-5) {
        tri.getNormal(_delta);
      } else {
        _delta.multiplyScalar(1 / len);
      }

      const depth = radius - dist;
      _seg.start.addScaledVector(_delta, depth);
      _seg.end.addScaledVector(_delta, depth);
      _tempBox.setFromPoints([_seg.start, _seg.end]);
      _box.copy(_tempBox);
      _box.min.addScalar(-radius);
      _box.max.addScalar(radius);
      return false;
    },
  });

  // Transform adjusted bottom cap point back to world feet position.
  _offset.copy(_seg.start).applyMatrix4(surface.matrixWorld);
  _offset.y -= radius;
  _worldNormal.subVectors(_offset, body.basePos);
  const pushLen = _worldNormal.length();
  if (pushLen > 1e-5) {
    _worldNormal.multiplyScalar(1 / pushLen);
    body.basePos.copy(_offset);
    if (_worldNormal.y >= MIN_FLOOR_NORMAL_Y) {
      body.grounded = true;
      if (body.velocity.y < 0) body.velocity.y = 0;
    } else {
      const vn = body.velocity.dot(_worldNormal);
      if (vn < 0) body.velocity.addScaledVector(_worldNormal, -vn);
    }
  }
}

export function stepCapsuleController(
  game: Game,
  body: CapsuleBody,
  surface: BvhColliderSurface,
): void {
  game.onUpdate((dt) => {
    const move = game.input.move;
    const speed = game.tuning.value('moveSpeed', 6.5);
    const gravity = game.tuning.value('gravity', 24);
    body.velocity.x = move.x * speed;
    body.velocity.z = -move.y * speed;
    body.velocity.y = body.grounded ? -0.2 : body.velocity.y - gravity * dt;

    body.basePos.addScaledVector(body.velocity, dt);
    resolveBvhCapsule(body, surface);

    // Optional downward snap probe when stepping down shallow ramps
    if (!body.grounded && body.velocity.y <= 0) {
      _origin.set(body.basePos.x, body.basePos.y + 0.2, body.basePos.z);
      _dir.set(0, -1, 0);
      const hit = surface.bvh.raycastFirst(
        new THREE.Ray(_origin.clone(), _dir.clone()),
        THREE.DoubleSide,
      );
      if (hit && hit.distance < 0.35 && hit.face && hit.face.normal.y >= MIN_FLOOR_NORMAL_Y) {
        body.basePos.y = hit.point.y;
        body.grounded = true;
        body.velocity.y = 0;
      }
    }
  });
}
```

> Note: Inside hot 60 Hz step paths (`stepCapsuleController`), prefer reusing a module-scope `_ray = new THREE.Ray()` with `_ray.set(_origin, _dir)` instead of allocating `new THREE.Ray` per frame so GC pauses never trigger in mobile WebGL.

## Browser & Mobile Performance

- **Indexed Static Merges**: Combine immovable cliff, bridge, and archway meshes with `StaticGeometryGenerator` once at level load so `shapecast` walks a single balanced BVH tree instead of testing dozens of separate objects.
- **Zero Per-Frame Heap Churn**: Keep scratch vectors, matrices, boxes, and `THREE.Ray` instances at module scope so 60 Hz capsule resolution creates zero GC pressure on Quest or mobile Safari.

## Verification Checklist

1. Walk diagonally into acute 45° corners and concave wall joins — verify the capsule slides cleanly without tunneling or jitter.
2. Run a play test moving a `CapsuleBody` down a 30° ramp and checking `grounded === true` on every step.

## Official references

- Garrett Johnson (three-mesh-bvh Shapecast & Capsule Collision)
- Christer Ericson (Real-Time Collision Detection — Segment-Triangle Closest Points)
