I have a THREE.js plane where the points are manipulated using Perlin noise to create terrain. I now need to implement physics for the camera to prevent it from falling through the plane.
My goal is to develop a function that can extract the vertices and faces from the mesh and transfer them to a CANNON body as a Convex Polyhedron. Here's my current attempt that is not functioning as expected:
function setPhysicsGeometry(mesh, body) {
const vertices = mesh.geometry.vertices;
const shape = new CANNON.ConvexPolyhedron();
vertices.forEach(function(vertex) {
vertex.z = 0;
shape.vertices.push(new CANNON.Vec3(vertex.x, vertex.y, vertex.z));
});
const faces = [];
for (let i = 0; i < mesh.geometry.faces.length; i++) {
const face = mesh.geometry.faces[i];
faces.push([face.a, face.b, face.c]);
}
shape.faces = faces;
shape.updateNormals();
shape.updateEdges();
body.addShape(shape);
}
I'm encountering the following error:
Uncaught TypeError: shape.updateNormals is not a function
The same issue arises with shape.updateEdges()
Is this a problem with these functions or am I oversimplifying a difficult/impossible task?
Thank you
UPDATE: I've created a function that somewhat functions but is extremely slow:
function createShape(geo) {
const bufferedGeo = new THREE.BufferGeometry().fromGeometry(geo);
let position = bufferedGeo.attributes.position.array
const points = []
for (let i = 0; i < position.length; i += 3) {
points.push(new CANNON.Vec3(position[i], position[i + 1], position[i + 2]))
}
const faces = []
for (let i = 0; i < position.length / 3; i += 3) {
faces.push([i, i + 1, i + 2])
}
const shape = new CANNON.ConvexPolyhedron(points, faces)
return shape
}
Here's an error I'm encountering indicating that the normals are incorrectly ordered:
.faceNormals[1011] = Vec3(-0.38237948261368415,0.4673447646702331,-0.7971040096570934) looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.
I'm unsure how to rectify this issue since the normals are simply derived from the geometry