Skip to content

Instantly share code, notes, and snippets.

@Anthelmed
Last active November 9, 2022 00:05
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Anthelmed/976bb456db0bb3bd42ecda5dfa482a66 to your computer and use it in GitHub Desktop.
Save Anthelmed/976bb456db0bb3bd42ecda5dfa482a66 to your computer and use it in GitHub Desktop.
Using v-hacd https://github.com/kmammou/v-hacd to create custom collider for cannon js
import THREE from 'three';
import CANNON from 'cannon';
export const generateThreeVertices = (rawVerts) => {
let verts = [];
for(let v = 0; v < rawVerts.length; v+=3){
verts.push(new THREE.Vector3(rawVerts[v],
rawVerts[v+1],
rawVerts[v+2]));
}
return verts;
};
export const generateThreeFaces = (rawFaces) => {
let faces = [];
for(let f = 0; f < rawFaces.length; f+=3){
faces.push(new THREE.Face3(rawFaces[f],
rawFaces[f+1],
rawFaces[f+2]));
}
return faces;
};
export const generateCannonVertices = (rawVerts) => {
let verts = [];
for(let v = 0; v < rawVerts.length; v++){
verts.push(new CANNON.Vec3(rawVerts[v].x,
rawVerts[v].y,
rawVerts[v].z));
}
return verts;
};
export const generateCannonFaces = (rawFaces) => {
let faces = [];
for(let f = 0; f < rawFaces.length; f++){
faces.push([rawFaces[f].a,
rawFaces[f].b,
rawFaces[f].c]);
}
return faces;
};
export const generateBody = (groups, properties) => {
const body = new CANNON.Body({
mass: properties.mass
});
for (let g = 0; g < groups.length; g++) {
const group = groups[g];
const verts = generateThreeVertices(group.vertices);
const faces = generateThreeFaces(group.faces);
const geometry = new THREE.Geometry();
const material = new THREE.MeshBasicMaterial();
geometry.vertices = verts;
geometry.faces = faces;
const mesh = new THREE.Mesh(geometry, material);
mesh.scale.copy(properties.scale);
mesh.updateMatrix();
mesh.geometry.applyMatrix(mesh.matrix);
mesh.geometry.computeFaceNormals();
mesh.geometry.computeVertexNormals();
mesh.matrix.identity();
const updatedVerts = generateCannonVertices(mesh.geometry.vertices);
const updatedFaces = generateCannonFaces(mesh.geometry.faces);
const polyhedron = new CANNON.ConvexPolyhedron(updatedVerts,updatedFaces);
body.addShape(polyhedron);
}
return body;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment