How to create exact sized shapes with ConvexPolyhedron in Cannon-es and Three.js

20 Views Asked by At

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, like this.


    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 normalsTetra = computeFaceNormals(vertices, faces);

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

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

And due to this for some reason the cannon js body and threejs shape are not getting aligned as can be seen in this image -

tetra

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?

0

There are 0 best solutions below