Logotipo de Threejs Impl Physics

Threejs Impl Physics

Organización
Impertio-Studio
threejs-impl-physics

Use when adding physics simulation to a Three.js scene: rigid bodies, collisions, constraints, or raycasting. Prevents the common mistake of wrong Vec3/Vector3 conversion, missing world.step(), or choosing the wrong engine. Covers cannon-es and Rapier with Three.js sync patterns, performance comparison. Keywords: physics, cannon-es, Rapier, rigid body, collider, collision, gravity, simulation, WASM, constraint, joint, objects fall, collision detection, bouncing, realistic movement.

Descripción general

EditorImpertio-Studio
RepositorioThree.js-Claude-Skill-Package
Nombre de la habilidadthreejs-impl-physics
Estrellas
29
Forks
3
Archivos incluidos
3
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando una petición es realmente relevante.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • 3 archivos incluidos

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por Impertio-Studio en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Threejs Impl Physics en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package/tree/master/skills/source/threejs-impl/threejs-impl-physics
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → Desde URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package.git /tmp/Three.js-Claude-Skill-Package
mkdir -p .claude/skills
cp -r /tmp/Three.js-Claude-Skill-Package/skills/source/threejs-impl/threejs-impl-physics .claude/skills/threejs-impl-physics
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Threejs Impl Physics en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición es relevante, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Threejs Impl Physics automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Threejs Impl Physics no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición relevante, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

threejs-impl-physics

Quick Reference

Engine Selection Decision Tree

Criterioncannon-esRapier
Scene size< 100 bodies100–10,000+ bodies
Determinism neededNoYes (cross-platform)
CCD (fast objects)LimitedFull support
Bundle size budget~100 KB~300–600 KB (WASM)
InitializationSynchronousAsync (MUST await init())
Prototyping speedFaster (simpler API)Slower (builder pattern)
R3F integration@react-three/cannon@react-three/rapier

Rule: ALWAYS use Rapier for production applications requiring determinism, CCD, or > 100 bodies. Use cannon-es for prototyping and simple scenes.

Critical Warnings

NEVER forget to call world.step() in the animation loop — physics bodies will NOT move without it.

NEVER use mesh.position.copy(body.position) with Rapier — Rapier returns plain {x, y, z} objects, NOT CANNON.Vec3. ALWAYS use mesh.position.set(pos.x, pos.y, pos.z).

NEVER use Rapier APIs before await RAPIER.init() completes — ALL Rapier classes are undefined until WASM loads.

NEVER use Trimesh / trimesh colliders on dynamic bodies — triangle meshes are STATIC only in both engines. Use ConvexPolyhedron / convexHull for dynamic concave geometry.

NEVER create physics bodies without corresponding Three.js meshes unless intentionally creating invisible colliders — orphaned bodies waste simulation budget.


cannon-es

World Setup

js
import * as CANNON from 'cannon-es';

const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
world.broadphase = new CANNON.SAPBroadphase(world);
world.solver.iterations = 10;
world.allowSleep = true;

ALWAYS set world.allowSleep = true — sleeping bodies skip simulation and dramatically improve performance.

ALWAYS use SAPBroadphase for scenes with > 20 bodies. NaiveBroadphase is O(n^2).

Body Types

TypeMassBehavior
CANNON.Body.DYNAMIC> 0Affected by forces and collisions
CANNON.Body.STATIC0Immovable, infinite mass
CANNON.Body.KINEMATIC0Moved programmatically, pushes dynamic bodies
js
const body = new CANNON.Body({
  mass: 5,
  position: new CANNON.Vec3(0, 10, 0),
  shape: new CANNON.Box(new CANNON.Vec3(1, 1, 1)), // half-extents
  linearDamping: 0.01,
  angularDamping: 0.01,
});
world.addBody(body);

Shape Types

ShapeConstructorNotes
Boxnew CANNON.Box(halfExtents: Vec3)Axis-aligned box
Spherenew CANNON.Sphere(radius)Cheapest collision shape
Cylindernew CANNON.Cylinder(rTop, rBottom, height, segments)Cylinder
Planenew CANNON.Plane()Infinite ground plane
ConvexPolyhedronnew CANNON.ConvexPolyhedron({vertices, faces})Custom convex hull
Trimeshnew CANNON.Trimesh(vertices, indices)STATIC only
Heightfieldnew CANNON.Heightfield(data, {elementSize})Terrain
Particlenew CANNON.Particle()Point particle

Materials and Contacts

js
const groundMat = new CANNON.Material('ground');
const ballMat = new CANNON.Material('ball');
const contact = new CANNON.ContactMaterial(groundMat, ballMat, {
  friction: 0.4,
  restitution: 0.6,
});
world.addContactMaterial(contact);

// Assign materials to bodies
groundBody.material = groundMat;
ballBody.material = ballMat;

ALWAYS assign materials to bodies after creating ContactMaterial — without assignment, the ContactMaterial has NO effect.

Constraints

ConstraintConstructorUse Case
PointToPointConstraint(bodyA, pivotA, bodyB, pivotB)Ball joint
DistanceConstraint(bodyA, bodyB, distance)Fixed distance rod
HingeConstraint(bodyA, bodyB, {pivotA, axisA, pivotB, axisB})Door hinge
LockConstraint(bodyA, bodyB)Rigid lock
ConeTwistConstraint(bodyA, bodyB, options)Ragdoll joints
Spring(bodyA, bodyB, options)Damped spring
js
const hinge = new CANNON.HingeConstraint(bodyA, bodyB, {
  pivotA: new CANNON.Vec3(0, 0, 0),
  axisA: new CANNON.Vec3(0, 1, 0),
  pivotB: new CANNON.Vec3(-2, 0, 0),
  axisB: new CANNON.Vec3(0, 1, 0),
});
world.addConstraint(hinge);

Events

js
body.addEventListener('collide', (event) => {
  const { contact } = event;
  // contact.ni = contact normal
  // contact.ri = contact point relative to bodyA
  // contact.rj = contact point relative to bodyB
});
body.addEventListener('sleep', () => { /* body went to sleep */ });
body.addEventListener('wakeup', () => { /* body woke up */ });

Stepping

js
// ALWAYS use three-argument step for deterministic simulation
const fixedTimeStep = 1 / 60;
const maxSubSteps = 3;

function animate() {
  const delta = clock.getDelta();
  world.step(fixedTimeStep, delta, maxSubSteps);
}

Rapier

WASM Initialization

js
import RAPIER from '@dimforge/rapier3d-compat';

await RAPIER.init(); // MUST await — ALL APIs undefined before this resolves

const gravity = { x: 0.0, y: -9.81, z: 0.0 };
const world = new RAPIER.World(gravity);

ALWAYS wrap Rapier usage in an async function or top-level await. Calling ANY Rapier constructor before init() resolves throws a runtime error.

RigidBody Creation (Builder Pattern)

js
// Dynamic body
const bodyDesc = RAPIER.RigidBodyDesc.dynamic()
  .setTranslation(0, 10, 0)
  .setLinvel(0, 0, 0)
  .setAngvel({ x: 0, y: 0, z: 0 })
  .setLinearDamping(0.01)
  .setAngularDamping(0.01)
  .setCcdEnabled(true);
const rigidBody = world.createRigidBody(bodyDesc);

// Static body
const staticDesc = RAPIER.RigidBodyDesc.fixed().setTranslation(0, 0, 0);
const staticBody = world.createRigidBody(staticDesc);

// Kinematic (position-based)
const kinDesc = RAPIER.RigidBodyDesc.kinematicPositionBased();
const kinBody = world.createRigidBody(kinDesc);

// Kinematic (velocity-based)
const kinVelDesc = RAPIER.RigidBodyDesc.kinematicVelocityBased();

Collider Shapes

js
const colliderDesc = RAPIER.ColliderDesc.cuboid(1, 1, 1)
  .setRestitution(0.5)
  .setFriction(0.7);
world.createCollider(colliderDesc, rigidBody);
ShapeConstructorNotes
ColliderDesc.cuboid(hx, hy, hz)Box half-extentsMost common
ColliderDesc.ball(radius)SphereCheapest shape
ColliderDesc.capsule(halfHeight, radius)CapsuleGood for characters
ColliderDesc.cylinder(halfHeight, radius)Cylinder
ColliderDesc.cone(halfHeight, radius)Cone
ColliderDesc.convexHull(vertices)Convex hullFrom Float32Array
ColliderDesc.trimesh(vertices, indices)Triangle meshSTATIC only
ColliderDesc.heightfield(nrows, ncols, heights, scale)Terrain
ColliderDesc.roundCuboid(hx, hy, hz, borderRadius)Rounded box

Ray Casting

js
const ray = new RAPIER.Ray({ x: 0, y: 10, z: 0 }, { x: 0, y: -1, z: 0 });
const hit = world.castRay(ray, 100, true);
if (hit) {
  const hitPoint = ray.pointAt(hit.timeOfImpact);
  const hitCollider = world.getCollider(hit.colliderHandle);
}

CCD (Continuous Collision Detection)

ALWAYS enable CCD on fast-moving bodies to prevent tunneling through thin geometry:

js
const desc = RAPIER.RigidBodyDesc.dynamic().setCcdEnabled(true);

Collision Events

js
const eventQueue = new RAPIER.EventQueue(true);
world.step(eventQueue);

eventQueue.drainCollisionEvents((handle1, handle2, started) => {
  // started === true: collision began
  // started === false: collision ended
});

eventQueue.drainContactForceEvents((event) => {
  const force = event.totalForceMagnitude();
});

Debug Rendering

js
const { vertices, colors } = world.debugRender();
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 4));
const material = new THREE.LineBasicMaterial({ vertexColors: true });
const lines = new THREE.LineSegments(geometry, material);
scene.add(lines);

Three.js Sync Pattern

cannon-es Sync

js
// Store body-mesh pairs
const pairs = [];

function addPhysicsObject(mesh, body) {
  scene.add(mesh);
  world.addBody(body);
  pairs.push({ mesh, body });
}

function updatePhysics(delta) {
  world.step(1 / 60, delta, 3);
  for (const { mesh, body } of pairs) {
    mesh.position.copy(body.position);       // Vec3 → Vector3 (compatible)
    mesh.quaternion.copy(body.quaternion);    // Quaternion → Quaternion (compatible)
  }
}

cannon-es Vec3 and Quaternion are directly compatible with Three.js .copy().

Rapier Sync

js
const pairs = [];

function addPhysicsObject(mesh, rigidBody) {
  scene.add(mesh);
  pairs.push({ mesh, rigidBody });
}

function updatePhysics() {
  world.step();
  for (const { mesh, rigidBody } of pairs) {
    const pos = rigidBody.translation();   // returns {x, y, z}
    const rot = rigidBody.rotation();      // returns {x, y, z, w}
    mesh.position.set(pos.x, pos.y, pos.z);
    mesh.quaternion.set(rot.x, rot.y, rot.z, rot.w);
  }
}

NEVER use .copy() with Rapier return values — they are plain objects, NOT Three.js types.


React Three Fiber Integration

@react-three/rapier

jsx
import { Physics, RigidBody } from '@react-three/rapier';

function Scene() {
  return (
    <Physics gravity={[0, -9.81, 0]}>
      <RigidBody type="fixed">
        <mesh position={[0, -1, 0]}>
          <boxGeometry args={[20, 1, 20]} />
          <meshStandardMaterial />
        </mesh>
      </RigidBody>
      <RigidBody>
        <mesh position={[0, 5, 0]}>
          <sphereGeometry args={[1]} />
          <meshStandardMaterial />
        </mesh>
      </RigidBody>
    </Physics>
  );
}

@react-three/cannon

jsx
import { Physics, useBox, useSphere } from '@react-three/cannon';

function Floor() {
  const [ref] = useBox(() => ({ mass: 0, args: [20, 1, 20], position: [0, -1, 0] }));
  return (
    <mesh ref={ref}>
      <boxGeometry args={[20, 1, 20]} />
      <meshStandardMaterial />
    </mesh>
  );
}

Performance Comparison

Featurecannon-esRapier
LanguageJavaScriptRust compiled to WASM
Real-time bodies~1,000~10,000+
Bundle size~100 KB~300–600 KB
CCDLimitedFull support
DeterministicNoYes (cross-platform)
Debug renderingManualBuilt-in world.debugRender()
API styleConstructor-basedBuilder pattern

Reference Links

Official Sources

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Se ofrecen como archivos de lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA Threejs Impl Physics?

Use when adding physics simulation to a Three.js scene: rigid bodies, collisions, constraints, or raycasting. Prevents the common mistake of wrong Vec3/Vector3 conversion, missing world.step(), or choosing the wrong engine. Covers cannon-es and Rapier with Three.js sync patterns, performance comparison. Keywords: physics, cannon-es, Rapier, rigid body, collider, collision, gravity, simulation, WASM, constraint, joint, objects fall, collision detection, bouncing, realistic movement.

¿Por qué usar Threejs Impl Physics en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Threejs Impl Physics está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Threejs Impl Physics en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package/tree/master/skills/source/threejs-impl/threejs-impl-physics. TypingMind lee su archivo SKILL.md, empaqueta sus archivos y la instala como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Threejs Impl Physics?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Threejs Impl Physics?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Threejs Impl Physics con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Threejs Impl Physics?

Sí. Impertio-Studio la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇