Problem with THREE.js with intersecting objects

I have a problem with detecting intersections of objects using THREE.js. My objects are extruded from 2D geometry, for example:

var geoShape = new THREE.Shape(vertexes); var geometry = new THREE.ExtrudeGeometry(geoShape, { bevelEnabled: false, amount: 3 }); var mesh = THREE.SceneUtils.createMultiMaterialObject(geometry, [new THREE.MeshLambertMaterial({ color: '#493D26' })] ); scene.add(mesh); 

Then I try to detect the intersection as follows:

 container.mousedown(function (e) { event.preventDefault(); var vector = new THREE.Vector3((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1, 0.5); projector.unprojectVector(vector, camera); var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); var intersects = raycaster.intersectObjects(scene.children); console.log(intersects); }); 

Each time my intersection array is empty. If I add a sphere to the scene, I get intersections, but only if I am enlarged to z <18. Any suggestions?

+4
source share
3 answers

Add true

 raycaster.intersectObjects(scene.children, true); 

From Documents:

recursive (true) - if set, it also checks all descendants. Otherwise, it only checks the intersection with the object.

+8
source

Some things can cause the raycaster to not be created correctly, the best way to debug it and make sure your raycaster is correct, I recommend you visualize it using: raycaster.ray.origin and raycaster.ray., The direction can be easily done also in the same mouse event that the intersection should detect:

 var material = new THREE.LineBasicMaterial({ color: 0x0000ff }); var geometry = new THREE.Geometry(); geometry.vertices.push(new THREE.Vector3(raycaster.ray.origin.x, raycaster.ray.origin.y, raycaster.ray.origin.z)); geometry.vertices.push(new THREE.Vector3(raycaster.ray.origin.x + (raycaster.ray.direction.x * 100000), raycaster.ray.origin.y + (raycaster.ray.direction.y * 100000), raycaster.ray.origin.z + (raycaster.ray.direction.z * 100000))); var line = new THREE.Line(geometry, material); 

NOTE. Please note that the beam will be visualized only if the camera’s point of view is changed!

+3
source

For me, the solution was the answer of a sucker ...

 raycaster.intersectObjects(scene.children, true); 

... PLUS the realization that raycaster creates an array of all intersections , not just the first. My code repeated through all intersections and displayed the last when I needed only the first. So that...

 var intersects = raycaster.intersectObjects( scene.children, true); if(intersects.length > 0) { //Do something with intersects[0]; } 
0
source

Source: https://habr.com/ru/post/1497620/


All Articles