How to create a cannonjs body with the exact size and orientation of a threejs shape

I’m trying to create a tetrahedron in Three.js along with a corresponding Cannon.js body using ConvexPolyhedron. However, I find myself having to guess the vertices and faces for the shape, which is causing problems like the one in the image above. The light blue tetrahedron is being created by cannon-es and the green one is by threejs and their orientation is not aligned for some reason.

image

Here is my code -

const tetrahedronGeometry = new THREE.TetrahedronGeometry(1); // Size of the tetrahedron

    const tetraMaterial = new THREE.MeshBasicMaterial({
      color: 0x00ff00,
      wireframe: true,
    }); // Green material

    const tetrahedron = new THREE.Mesh(tetrahedronGeometry, tetraMaterial);

    scene.add(tetrahedron);


    const vertices = [
      new CANNON.Vec3(1, 0, 0), // Vertex 0
      new CANNON.Vec3(-0.5, Math.sqrt(3) / 2, 0), // Vertex 1
      new CANNON.Vec3(-0.5, -Math.sqrt(3) / 2, 0), // Vertex 2
      new CANNON.Vec3(0, 0, 1), // Vertex 3
    ];

    const faces = [
      [0, 1, 2], // Face 0 (triangle)
      [0, 3, 1], // Face 1 (triangle)
      [0, 2, 3], // Face 2 (triangle)
      [1, 2, 3], // Face 3 (triangle)
    ];

    const tetrahedronShape = new CANNON.ConvexPolyhedron({
      vertices,
      faces,
    });

   const tetrahedronBody = new CANNON.Body({
      mass: 2, // Set mass
      shape: tetrahedronShape,
      position: new CANNON.Vec3(0, 10, 0),
    });

Is there a method to programmatically align the Cannon.js body precisely with the size and orientation of the corresponding Three.js shape, rather than relying on manual estimation of vertices and faces?

Hi!
Specifically for a tetrahedron, you can see the source code of TetrahedronGeometry: three.js/src/geometries/TetrahedronGeometry.js at ef80ac74e6716a50104a57d8add6c8a950bff8d7 · mrdoob/three.js · GitHub
Use that information for creation of a cannonjs body.

Or create your own geometry, aligned with a cannonjs body. Something like this: Tetrahedron (non-indexed buffer geometry)

1 Like

thanks! this worked !!

2 Likes