Triggers & Collision Events
Half of game logic is "when X touches Y, do Z": pick up the coin, open the door when the player steps on the plate, start the cutscene when the player enters the room, damage the player when the spikes touch them, play a thud when a crate lands. Physics engines report this in two ways:
- Sensors (also called triggers): colliders that detect overlaps but never push anything. Coins, checkpoints, doorways, kill zones, aggro radii.
- Contact events between solid colliders: impacts, landings, hits, with forces if you need them for sound volume or damage.
Enter, stay, exit
Game code usually wants edges: one event when something enters, one when it leaves, and maybe "is it inside right now?". Engines give you start/stop events; keep the "inside" set yourself. This plain-JS model tracks a player walking through two circular zones (in a real game the physics engine detects the overlaps):
// Trigger bookkeeping: report enter/exit edges from per-step overlap tests.
const zones = [{ name: 'campfire', x: 3, r: 1.5 }, { name: 'shop', x: 6, r: 1 }];
const inside = new Set();
for (let step = 0; step <= 16; step++) {
const px = step * 0.5; // the player walks along +x
for (const z of zones) {
const overlapping = Math.abs(px - z.x) < z.r;
if (overlapping && !inside.has(z.name)) { inside.add(z.name); console.log(`x=${px.toFixed(1)} enter ${z.name}`); }
if (!overlapping && inside.has(z.name)) { inside.delete(z.name); console.log(`x=${px.toFixed(1)} exit ${z.name}`); }
}
}
console.log('still inside:', [...inside].join(', ') || 'nothing');x=2.0 enter campfire
x=4.5 exit campfire
x=5.5 enter shop
x=7.0 exit shop
still inside: nothing
At x = 4.5 the player is exactly 1.5 m from the campfire, the radius, which counts as outside because the test is <. Engines have the same kind of edge cases, which is why a trigger that a character stands exactly on the edge of can flicker between enter and exit. Make trigger zones a bit larger than they look and act on enter, not on every frame of overlap.
Sensors in Rapier
Three steps: mark the collider as a sensor, ask for events, and pass an EventQueue to world.step:
const coin = world.createCollider(
RAPIER.ColliderDesc.ball(0.5)
.setTranslation(3, 1, 0)
.setSensor(true) // overlaps only, no pushing
.setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS) // report start/stop
.setActiveCollisionTypes(RAPIER.ActiveCollisionTypes.DEFAULT | RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED),
);
const events = new RAPIER.EventQueue(true);
world.step(events);
events.drainCollisionEvents((handle1, handle2, started) => {
// handles identify colliders; look up your game objects by handle
});The last line of the description is the trap almost everyone falls into: by default Rapier only detects pairs that involve a dynamic body (ActiveCollisionTypes.DEFAULT). A kinematic character controller walking into a sensor that has no body (fixed) is a kinematic–fixed pair, which is skipped. No error, just no events. Add KINEMATIC_FIXED (and KINEMATIC_KINEMATIC for moving sensors) to the sensor or to the character's collider.
This scripted run moves a kinematic capsule through two sensors, only one of which has the extra collision type, and prints the events (in the console under the frame):
<script type="module">
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
const events = new RAPIER.EventQueue(true);
const names = new Map(); // collider handle -> name
function sensor(name, x, extraTypes) {
let desc = RAPIER.ColliderDesc.cuboid(0.5, 1, 1).setTranslation(x, 1, 0)
.setSensor(true).setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS);
if (extraTypes) desc = desc.setActiveCollisionTypes(RAPIER.ActiveCollisionTypes.DEFAULT | RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED);
names.set(world.createCollider(desc).handle, name);
}
sensor('default-types sensor', 2, false);
sensor('KINEMATIC_FIXED sensor', 5, true);
const player = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(0, 1, 0));
names.set(world.createCollider(RAPIER.ColliderDesc.capsule(0.5, 0.3), player).handle, 'player');
for (let step = 1; step <= 80; step++) {
const p = player.translation();
player.setNextKinematicTranslation({ x: p.x + 0.1, y: p.y, z: p.z }); // walk +x at 6 m/s
world.step(events);
events.drainCollisionEvents((h1, h2, started) => {
const other = names.get(h1) === 'player' ? names.get(h2) : names.get(h1);
console.log(`step ${String(step).padStart(2)} x=${player.translation().x.toFixed(1)} ${started ? 'ENTER' : 'EXIT '} ${other}`);
});
}
console.log('the default-types sensor never reported anything');
events.free();
world.free();
</script>Expected output:
step 43 x=4.3 ENTER KINEMATIC_FIXED sensor
step 60 x=6.0 EXIT KINEMATIC_FIXED sensor
the default-types sensor never reported anythingThe player's capsule is 0.3 m in radius and the sensor box spans x = 4.5…5.5. The enter event arrives once the capsule's front has crossed 4.5, and the exit event a little after its back has left 5.5: events are reported per step, and the engine keeps small contact margins, so they come a step or two either side of the exact geometric moment. Design triggers so that doesn't matter.
Tip: Instead of events, you can also ask:
world.intersectionPairsWith(collider, (other) => …)lists the sensors a collider currently overlaps, which is handy for "is the player in water?" checks every frame. The same collision-type rules apply.
Collecting coins and opening a gate
A playable version: walk with WASD. The coins are sensors that disappear on enter. The blue pressure plate is a sensor too: the gate opens while you stand on it (enter) and closes when you step off (exit), and it also opens while a pushed crate sits on the plate. The gate is a kinematic body moved by a tween-like rule.
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #0e1018; }
canvas { display: block; outline: none; touch-action: none; }
#hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; pointer-events: none; text-shadow: 0 1px 2px #000; }
#veil { position: fixed; inset: 0; display: grid; place-content: center; background: rgba(0, 0, 0, 0.55); color: #fff; font: 600 20px system-ui, sans-serif; text-align: center; pointer-events: none; }
#veil small { display: block; margin-top: 6px; font-weight: 400; font-size: 13px; }
#veil.off { display: none; }
</style>
<div id="hud"></div>
<div id="veil">Click to play<small>WASD to move: collect coins, stand on the plate</small></div>
<script type="module">
import * as THREE from 'three';
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();
// ---- 3D play kit: renderer, click to focus, keys, pause on blur, fixed-step loop ----
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const cv = renderer.domElement, veil = document.getElementById('veil');
const keys = new Set(), pressed = new Set(); // held now / pressed since the last update
let active = false, drawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; veil.classList.add('off'); });
cv.addEventListener('blur', () => { active = false; drawn = false; veil.classList.remove('off'); keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(scene, camera, update) {
const STEP = 1 / 60, timer = new THREE.Timer();
let acc = 0;
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
drawn = false;
});
renderer.setAnimationLoop((t) => {
timer.update(t);
if (active) {
acc += Math.min(timer.getDelta(), 0.1);
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
} else if (drawn) return; // paused: the last frame stays on screen
renderer.render(scene, camera);
drawn = true;
});
}
// ---- end of play kit ----
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1f2838');
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 11, 9);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#334', 1.4));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(3, 8, 4);
scene.add(sun);
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
const events = new RAPIER.EventQueue(true);
const SENSOR_TYPES = RAPIER.ActiveCollisionTypes.DEFAULT | RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED;
const byHandle = new Map(); // collider handle -> game object
function staticBox(w, h, d, x, y, z, color) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), new THREE.MeshStandardMaterial({ color }));
m.position.set(x, y, z);
scene.add(m);
world.createCollider(RAPIER.ColliderDesc.cuboid(w / 2, h / 2, d / 2).setTranslation(x, y, z));
}
staticBox(16, 1, 12, 0, -0.5, 0, '#4b5d45');
staticBox(16, 1.5, 0.5, 0, 0.75, -6, '#8a8174');
staticBox(16, 1.5, 0.5, 0, 0.75, 6, '#8a8174');
staticBox(0.5, 1.5, 12, -8, 0.75, 0, '#8a8174');
staticBox(0.5, 1.5, 12, 8, 0.75, 0, '#8a8174');
staticBox(0.5, 1.5, 4.5, 4, 0.75, -3.75, '#8a8174'); // dividing wall with a gap for the gate
staticBox(0.5, 1.5, 4.5, 4, 0.75, 3.75, '#8a8174');
// Gate: a kinematic body that slides down into the floor when open.
const gateBody = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(4, 0.75, 0));
world.createCollider(RAPIER.ColliderDesc.cuboid(0.2, 0.75, 1.5), gateBody);
const gate = new THREE.Mesh(new THREE.BoxGeometry(0.4, 1.5, 3), new THREE.MeshStandardMaterial({ color: '#b0503c' }));
scene.add(gate);
// Pressure plate sensor.
const plate = new THREE.Mesh(new THREE.BoxGeometry(1.6, 0.06, 1.6), new THREE.MeshStandardMaterial({ color: '#2f7fd8', emissive: '#000' }));
plate.position.set(-4, 0.03, 3);
scene.add(plate);
const plateCol = world.createCollider(RAPIER.ColliderDesc.cuboid(0.8, 0.4, 0.8).setTranslation(-4, 0.4, 3)
.setSensor(true).setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS).setActiveCollisionTypes(SENSOR_TYPES));
byHandle.set(plateCol.handle, { type: 'plate' });
let onPlate = 0; // how many things stand on it
// Coins: sensors in both rooms.
const coinGeo = new THREE.CylinderGeometry(0.3, 0.3, 0.08, 24).rotateX(Math.PI / 2);
const coinMat = new THREE.MeshStandardMaterial({ color: '#ffc928', emissive: '#4a3500' });
let coinsLeft = 0;
for (const [x, z] of [[-5, -3], [-1, -4], [0, 2], [6, -3], [6, 3]]) {
const mesh = new THREE.Mesh(coinGeo, coinMat);
mesh.position.set(x, 0.6, z);
scene.add(mesh);
const col = world.createCollider(RAPIER.ColliderDesc.ball(0.4).setTranslation(x, 0.6, z)
.setSensor(true).setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS).setActiveCollisionTypes(SENSOR_TYPES));
byHandle.set(col.handle, { type: 'coin', mesh, col });
coinsLeft++;
}
// A dynamic crate that can hold the plate down.
const crateBody = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(-1.5, 0.45, 3).setLinearDamping(2));
world.createCollider(RAPIER.ColliderDesc.cuboid(0.45, 0.45, 0.45), crateBody);
const crate = new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.9, 0.9), new THREE.MeshStandardMaterial({ color: '#c58a3c' }));
scene.add(crate);
// Player with a character controller.
const playerBody = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(-6, 0.8, 0));
const playerCol = world.createCollider(RAPIER.ColliderDesc.capsule(0.35, 0.35), playerBody);
byHandle.set(playerCol.handle, { type: 'player' });
const controller = world.createCharacterController(0.02);
controller.setApplyImpulsesToDynamicBodies(true);
controller.enableSnapToGround(0.3);
const player = new THREE.Mesh(new THREE.CapsuleGeometry(0.35, 0.7, 4, 12), new THREE.MeshStandardMaterial({ color: '#ff7043' }));
scene.add(player);
const hud = document.getElementById('hud');
let gateY = 0.75, vy = 0;
function handleEvent(h1, h2, started) {
const a = byHandle.get(h1), b = byHandle.get(h2);
const trigger = a?.type === 'coin' || a?.type === 'plate' ? a : b;
const other = trigger === a ? b : a;
if (trigger?.type === 'coin' && other?.type === 'player' && started && trigger.mesh.visible) {
trigger.mesh.visible = false;
world.removeCollider(trigger.col, false); // no more events from this coin
coinsLeft--;
}
if (trigger?.type === 'plate') onPlate += started ? 1 : -1; // player or crate
}
run(scene, camera, (dt) => {
const ix = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
const iz = (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0) - (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0);
const len = Math.hypot(ix, iz) || 1;
vy = controller.computedGrounded() ? 0 : vy - 20 * dt;
controller.computeColliderMovement(playerCol, { x: (ix / len) * 4 * dt, y: vy * dt, z: (iz / len) * 4 * dt },
RAPIER.QueryFilterFlags.EXCLUDE_SENSORS); // walk through sensors instead of bumping into them
const m = controller.computedMovement(), p = playerBody.translation();
playerBody.setNextKinematicTranslation({ x: p.x + m.x, y: p.y + m.y, z: p.z + m.z });
// The gate slides toward its target height: down when the plate is pressed.
const target = onPlate > 0 ? -0.8 : 0.75;
gateY += Math.sign(target - gateY) * Math.min(Math.abs(target - gateY), 3 * dt);
gateBody.setNextKinematicTranslation({ x: 4, y: gateY, z: 0 });
world.step(events);
events.drainCollisionEvents(handleEvent);
const pp = playerBody.translation(), cp = crateBody.translation(), cq = crateBody.rotation();
player.position.set(pp.x, pp.y, pp.z);
crate.position.set(cp.x, cp.y, cp.z);
crate.quaternion.set(cq.x, cq.y, cq.z, cq.w);
gate.position.set(4, gateY, 0);
plate.material.emissive.set(onPlate > 0 ? '#1d4f8a' : '#000000');
hud.textContent = coinsLeft ? `Coins left: ${coinsLeft} plate: ${onPlate > 0 ? 'pressed' : 'up'}` : 'All coins collected!';
});
const sp = playerBody.translation();
player.position.set(sp.x, sp.y, sp.z);
const cp0 = crateBody.translation();
crate.position.set(cp0.x, cp0.y, cp0.z);
gate.position.set(4, gateY, 0);
hud.textContent = `Coins left: ${coinsLeft}`;
</script>Note the third argument of computeColliderMovement: the character controller treats sensors as obstacles unless you exclude them with RAPIER.QueryFilterFlags.EXCLUDE_SENSORS. Without it, the player stops at the edge of the plate and every coin, as if they were walls.
Two coins sit behind the gate. Push the crate onto the plate to keep the gate open while you walk through: the plate counts how many things are on it (onPlate), so it stays pressed until the last one leaves. Counting enters and exits instead of storing a boolean is what makes multi-object triggers work.
Triggers in cannon-es
cannon-es has the same idea with isTrigger: the body detects contacts but doesn't respond to them.
const zone = new CANNON.Body({ isTrigger: true, type: CANNON.Body.STATIC, shape: new CANNON.Box(new CANNON.Vec3(1, 1, 1)) });
world.addBody(zone);
zone.addEventListener('collide', (e) => { if (e.body === playerBody) onEnterZone(); });
world.addEventListener('beginContact', (e) => { /* e.bodyA, e.bodyB */ });
world.addEventListener('endContact', (e) => { /* … */ });Contact events for gameplay
Solid colliders can report contacts too (setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS) on a normal collider), and Rapier can additionally report contact forces (ActiveEvents.CONTACT_FORCE_EVENTS with setContactForceEventThreshold, drained with drainContactForceEvents): play a soft or loud impact sound depending on the force, or break a crate only when it's hit hard. Keep event-producing colliders to the ones that need them; every reported pair costs a little.
Test yourself
A kinematic character walks into a fixed Rapier sensor and no events arrive. What is missing?
setSensor(false)ActiveCollisionTypes.KINEMATIC_FIXEDon the sensor or the character's collider- A dynamic body on the sensor
world.timestep = 1/120
Why does the pressure plate count enters and exits (onPlate += started ? 1 : -1) instead of storing pressed = started?
- It's faster
- Several objects can be on it; a boolean would release the plate when the first of them leaves
- Rapier requires counters
- To avoid tunnelling
What distinguishes a sensor (trigger) from a normal collider?
- Sensors are invisible
- Sensors detect overlaps and report events but never push or block anything
- Sensors only work with spheres
- Sensors must be dynamic