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.
- collision
- bvh
- capsule
- physics
- mesh
- slopes
- spatial-hash
- threejs
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:
- 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). Nevernewmath or geometry objects insidegame.onUpdate. - Accumulate Contacts Over
shapecast: Letbvh.shapecastvisit 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. - Separate Slope Walkability from Wall Pushout: Classify any floor contact whose normal satisfies
n_y ≥ cos(θ_max)(default45°,n_y ≥ 0.707) as walkable ground and zero downward velocity; project wall contacts alongnso running diagonally into curved walls slides smoothly without snagging.
Mathematical & Algorithmic Core
- Capsule Penetration Vector: For segment point
p_sand closest triangle pointp_twith distanced = \|p_s - p_t\| < r: $Δ p = fracp_s - p_tmax(d, 10^-5) · (r - d)$ - Wall Sliding: Remove only the inward velocity component along horizontal wall normal
nwhenv · n < 0: $v' = v - (v · n)n$
Engine Implementation
Zero-Allocation MeshBVH Capsule Sweep Solver (Assets/Game/bvh-capsule.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
StaticGeometryGeneratoronce at level load soshapecastwalks a single balanced BVH tree instead of testing dozens of separate objects. - Zero Per-Frame Heap Churn: Keep scratch vectors, matrices, boxes, and
THREE.Rayinstances at module scope so 60 Hz capsule resolution creates zero GC pressure on Quest or mobile Safari.
Verification Checklist
- Walk diagonally into acute 45° corners and concave wall joins — verify the capsule slides cleanly without tunneling or jitter.
- Run a play test moving a
CapsuleBodydown a 30° ramp and checkinggrounded === trueon every step.
Official references
- Garrett Johnson (three-mesh-bvh Shapecast & Capsule Collision)
- Christer Ericson (Real-Time Collision Detection — Segment-Triangle Closest Points)
Playable Three.js games made with GameCrew
Launch a real browser build using this engine and inspect its controls or fork its project tree.
More Three.js techniques
Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →
Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.
Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2) →
Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.
Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →
Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.
Multiplayer Room State Sync & 60 Hz Avatars in Three.js →
Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.
Use verified techniques inside a real game
Describe your game idea for free or connect an MCP assistant to search and contribute techniques.
