mrK
mrK

Reputation: 2278

THREE.js issue with intersecting objects

I'm having an issue detecting object intersections with THREE.js. My objects are being extruded from a 2D geometry like such:

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);

I am then trying to detect intersection like this:

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);
});

Everytime, my intersects array is empty. If I add a sphere to the scene, I get intersections, but only if I am zoomed in to z < 18. Any suggestions?

Upvotes: 4

Views: 7850

Answers (3)

fivedogit
fivedogit

Reputation: 8524

For me, the solution was uhura's answer...

raycaster.intersectObjects(scene.children, true);

... PLUS the realization that the the raycaster generates an array of all intersections, not just the first one. My code was iterating through all intersections and displaying the last one, when I wanted the first one only. So...

var intersects = raycaster.intersectObjects( scene.children, true);

if(intersects.length > 0)
{
//Do something with intersects[0];
}   

Upvotes: 0

juagicre
juagicre

Reputation: 1074

Several things can be causing the raycaster not to be build up properly, the best way to debug it and to be sure your raycaster is the right one I recommend you to visualize it using: raycaster.ray.origin and raycaster.ray.direction, the line can be drawn easily like this in the same mouse event that should detect the intersection:

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: Take into account that the ray will be visualized just if the camera point of view is changed!

Upvotes: 3

uhura
uhura

Reputation: 2683

Add true

raycaster.intersectObjects(scene.children, true);

From Docs:

recursive (true) — If set, it also checks all descendants. Otherwise it only checks intersecton with the object.

Upvotes: 11

Related Questions