1

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?

1 Answer 1

0

This works for me:

    function createTetra() {
        var scale = 1;
        var verts = [
            new CANNON.Vec3(scale * 0, scale * 0, scale * 0),
            new CANNON.Vec3(scale * 1, scale * 0, scale * 0),
            new CANNON.Vec3(scale * 0, scale * 1, scale * 0),
            new CANNON.Vec3(scale * 0, scale * 0, scale * 1)];

        var offset = -0.35;
        for(var i = 0;i < verts.length;i++) {
            var v = verts[i];
            v.x += offset;
            v.y += offset;
            v.z += offset;
        }
        return new CANNON.ConvexPolyhedron(verts,
            [
                [0, 3, 2], // -x
                [0, 1, 3], // -y
                [0, 2, 1], // -z
                [1, 2, 3], // +xyz
            ]);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.