How to detect exactly collision of a Mesh has children

Now I’m checking the collision between Mesh.
I use Vertex and Raycaster to detect the collision.

const spheres = editor.scene.children; // list object from scene
const box1 = spheres[0];
if (box1.children.length > 0) {
   box1.traverse((item) => {
   if (item.isMesh) {
        const originPoint = new Vector3();
	item.getWorldPosition(originPoint);
        var vertices = [];
	const positionAttribute = item.geometry.getAttribute( 'position' );
	for ( let vertexIndex = 0; vertexIndex < positionAttribute.count; vertexIndex ++ ) {
		const vertex = new THREE.Vector3();
		vertex.fromBufferAttribute( positionAttribute, vertexIndex );
		vertices.push(vertex)
	}
	for (var vertexIndex = 0; vertexIndex < vertices.length; vertexIndex++) {
                var localVertex = vertices[vertexIndex];
		var globalVertex = localVertex.applyMatrix4(item.matrix);
		var directionVector = globalVertex.sub(originPoint);
		var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize(),true);
		var collisionResults = ray.intersectObjects(spheres);
                collisionResults = collisionResults.filter(function(element) {
			return element.distance < directionVector.length();
		});
		if (collisionResults.length > 0 ) {
			console.log('HIT: '+collisionResults);
		        break;
		}
	}}})
}

This is my result

  • When I drag box1(box1 is block that I selecting, white color) outside box2(blue color). The fact that is not collision. But its notice that collision in console

No collision
The result:
Result when no collision in fact

I reference: https://stackoverflow.com/questions/32067870/raycasting-as-collision-detector-not-accurate?rq=3 to do it.

How can I check the collision with Mesh has children?
Thank you~

Use mesh-bvh shapecast perhaps? :

https://gkjohnson.github.io/three-mesh-bvh/example/bundle/shapecast.html

3 Likes