Skip to main content
rule CX Codex

physics-integration — Claude Code rule: what it does, how to install

physics-integration guides Three.js integration with Rapier and Cannon-es: Vite setup, collider primitives, and mesh synchronization patterns.

MIT ★ 4,719 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/physics-integration.md
Open on GitHub

What physics-integration does

This rule equips coding assistants with patterns for integrating 3D physics engines into Three.js projects. It provides boilerplates for both @dimforge/rapier3d and cannon-es, categorizing body types, collider shapes, and material contact properties. For Vite setups, it specifies vite-plugin-wasm alongside vite-plugin-top-level-await so Rapier loads cleanly.

The guide enforces strict one-way synchronization from physics bodies to visual meshes to prevent feedback loops. It also details simulation constraints: maintaining a fixed 1/60 timestep, enabling body sleep for static objects, and hooking up cannon-es-debugger for contact inspection.

What it helps with

  • configure Rapier WASM loading in Vite projects
  • sync Three.js mesh positions with physics bodies without loops
  • create primitive and compound colliders for 3D meshes
  • enable contact debugging using cannon-es-debugger

Example prompts for the agent

  • Set up a Rapier physics world with gravity and a bouncing sphere
  • Wire up Cannon-es to animate Three.js boxes with fixed timesteps
  • Show how to sync kinematic bodies with Three.js meshes

How to install physics-integration

Manually: put the files in place

.claude/rules/physics-integration.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about physics-integration

How to install physics-integration in Claude Code?

Add the rule file directly to your project repository at .claude/rules/physics-integration.md.

What does physics-integration do?

It provides your AI agent with implementation rules for combining Three.js with Rapier and Cannon-es, preventing common sync issues.

Which dependencies are required for Rapier under Vite?

You need @dimforge/rapier3d, vite-plugin-wasm, and vite-plugin-top-level-await inside your build configuration.

Source text

physics-integration.md · MIT
# Physics Integration

Guide to integrating physics engines with Three.js.

## Engine Comparison

| Engine | Language | Characteristics | Performance |
|--------|----------|-----------------|-------------|
| **Rapier** | Rust/WASM | Deterministic, modern | Very High |
| **Cannon-es** | JavaScript | Easy to use, maintained fork | High |
| **Ammo.js** | C++/WASM | Bullet port, softbody support | Medium-High |

## Rapier (Recommended for 2025+)

### Setup

```bash
npm install @dimforge/rapier3d
```

### Vite Configuration

```javascript
// vite.config.js
import wasm from 'vite-plugin-wasm';
import topLevelAwait from 'vite-plugin-top-level-await';

export default {
  plugins: [wasm(), topLevelAwait()]
};
```

### Basic Usage

```javascript
import RAPIER from '@dimforge/rapier3d';

await RAPIER.init();
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });

// Create rigid body
const rigidBodyDesc = RAPIER.RigidBodyDesc.dynamic()
  .setTranslation(0, 5, 0);
const rigidBody = world.createRigidBody(rigidBodyDesc);

// Add collider
const colliderDesc = RAPIER.ColliderDesc.ball(0.5);
world.createCollider(colliderDesc, rigidBody);

// Sync with Three.js mesh
function animate() {
  world.step();

  const position = rigidBody.translation();
  const rotation = rigidBody.rotation();

  mesh.position.set(position.x, position.y, position.z);
  mesh.quaternion.set(rotation.x, rotation.y, rotation.z, rotation.w);
}
```

### Collider Shapes

```javascript
RAPIER.ColliderDesc.ball(radius)
RAPIER.ColliderDesc.cuboid(hx, hy, hz)
RAPIER.ColliderDesc.capsule(halfHeight, radius)
RAPIER.ColliderDesc.cylinder(halfHeight, radius)
RAPIER.ColliderDesc.cone(halfHeight, radius)
RAPIER.ColliderDesc.convexHull(vertices)
RAPIER.ColliderDesc.trimesh(vertices, indices)
```

## Cannon-es

### Setup

```bash
npm install cannon-es
```

### Basic Usage

```javascript
import * as CANNON from 'cannon-es';

const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);

const sphereBody = new CANNON.Body({
  mass: 1,
  shape: new CANNON.Sphere(0.5),
  position: new CANNON.Vec3(0, 5, 0)
});
world.addBody(sphereBody);

function animate() {
  world.step(1/60);
  mesh.position.copy(sphereBody.position);
  mesh.quaternion.copy(sphereBody.quaternion);
}
```

### Body Types

```javascript
// Dynamic (affected by forces)
new CANNON.Body({ mass: 1 })

// Static (immovable, mass = 0)
new CANNON.Body({ mass: 0 })

// Kinematic (controlled programmatically)
new CANNON.Body({
  mass: 0,
  type: CANNON.Body.KINEMATIC
})
```

### Shapes

```javascript
new CANNON.Sphere(radius)
new CANNON.Box(new CANNON.Vec3(hx, hy, hz))
new CANNON.Cylinder(radiusTop, radiusBottom, height, segments)
new CANNON.Plane()
new CANNON.ConvexPolyhedron({ vertices, faces })
new CANNON.Trimesh(vertices, indices)
```

## Sync Pattern

### BAD - Bidirectional sync

```javascript
// Physics affects mesh
mesh.position.copy(body.position);
// Mesh affects physics (creates feedback loop)
body.position.copy(mesh.position);
```

### GOOD - Physics -> Visual only

```javascript
function syncPhysicsToMesh(body, mesh) {
  mesh.position.copy(body.position);
  mesh.quaternion.copy(body.quaternion);
}

// For kinematic bodies controlled by Three.js
function syncMeshToKinematic(mesh, body) {
  body.position.copy(mesh.position);
  body.quaternion.copy(mesh.quaternion);
}
```

## Best Practices

1. **Simple Shapes**: Use simple colliders (box, sphere) even for complex meshes

2. **Fixed Timestep**: Use fixed timestep for physics (1/60)
   ```javascript
   world.step(1/60, deltaTime, 3); // Fixed step, max substeps
   ```

3. **Sleep**: Enable sleep for static bodies
   ```javascript
   body.allowSleep = true;
   body.sleepSpeedLimit = 0.1;
   ```

4. **Broad Phase**: Configure appropriate broad phase
   ```javascript
   world.broadphase = new CANNON.SAPBroadphase(world);
   ```

5. **Material Friction**: Define physics materials
   ```javascript
   const material = new CANNON.Material('default');
   const contact = new CANNON.ContactMaterial(material, material, {
     friction: 0.3,
     restitution: 0.3
   });
   world.addContactMaterial(contact);
   ```

6. **Sync Direction**: Always sync physics -> visual, not reverse

7. **Compound Shapes**: Use compound shapes for complex objects
   ```javascript
   const body = new CANNON.Body({ mass: 1 });
   body.addShape(new CANNON.Box(size1), offset1);
   body.addShape(new CANNON.Sphere(radius), offset2);
   ```

## Debug Visualization

```javascript
import CannonDebugger from 'cannon-es-debugger';

const cannonDebugger = CannonDebugger(scene, world);

function animate() {
  world.step(1/60);
  cannonDebugger.update();
}
```

## References

- [Rapier Documentation](https://rapier.rs/)
- [Cannon-es GitHub](https://github.com/pmndrs/cannon-es)
- [Three.js + Physics Examples](https://threejs.org/examples/?q=physics)

© zebbern · MIT · zebbern/claude-code-guide

Similar IDE rules

All IDE rules for Game dev and 3D: Unity, Unreal, Godot, Blender →

From the same set86

The whole set →
tsl-post-processing A reference rule for TSL post-processing in Three.js: chain effects onto postProcessing.outputNode instead of stacking EffectComposer passes. CX Codex +1 ★ 4,719repo stars tsl-compute-shaders tsl-compute-shaders guides the agent in writing WebGPU compute shaders with Three.js TSL for GPGPU tasks like particle systems and physics. CX Codex +1 ★ 4,719repo stars animation-system animation-system — a practical guide to Three.js animation, from playing and blending clips to morph targets and bones. Useful when building scenes with animated models. CX Codex +1 ★ 4,719repo stars gltf-loading-optimization gltf-loading-optimization is a Claude Code rule with Three.js snippets and commands for glTF loading, decoder setup, progress reporting, lazy loading and model compression. CX Codex +1 ★ 4,719repo stars raycasting-optimization The raycasting-optimization rule covers ways to reduce Three.js raycasting work, from filtering objects by layer to using BVH or GPU picking. Useful when a scene has complex meshes or frequent pointer checks. CX Codex +1 ★ 4,719repo stars mobile-optimization mobile-optimization is a rule for accelerating Three.js scenes on smartphones and tablets. It reduces GPU load and memory use, helping maintain a stable frame rate. CX Codex +1 ★ 4,719repo stars webxr-setup The webxr-setup rule for Claude Code guides building VR and AR scenes in Three.js WebXR. It helps coding agents set up render loops, controllers, and hit-testing. CX Codex +1 ★ 4,719repo stars error-handling-recovery The error-handling-recovery rule covers WebGL context loss, resource rebuilding, and fallback UI. Use it when a Three.js scene must recover from graphics failures. CX Codex +1 ★ 4,719repo stars

Project sponsors

Companies that keep this analytics open