Last active
November 9, 2022 00:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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