简体   繁体   中英

Three.JS - Raycasting on custom mesh


I'm currently trying to raycast a custom created mesh in three.js. While raycasting works like a charm for some imported meshes, it just doesn't seem to work at all with my custom mesh.

After researching for quite a while I found some typical issues for custom raycasting and tried to fix them (updateMatrixWorld, double side material, ... - see code below).

I'm using the following function for my raycasting:

mouse.x = ((e.clientX - container.offsetLeft) / container.clientWidth) * 2 - 1;
mouse.y = -((e.clientY - container.offsetTop) / container.clientHeight) * 2 + 1;

rayCaster.setFromCamera(mouse, camera);
var intersect = rayCaster.intersectObjects(scene.getObjectByName('loaded_object').children, true); // working


mesh_1.geometry.computeFaceNormals();
mesh_1.updateMatrixWorld();
var intersect_custom = rayCaster.intersectObjects([mesh_1], true); // not working

While the first intersect is working as expected, my custom intersect somehow doesn't work at all - it always returns an empty array.
Am I right with my assumption that the problem must be my custom mesh?

So here's how I created my custom mesh:

material_k1.side = THREE.DoubleSide;
var singleGeometry_1 = new THREE.Geometry();
var mesh_1 = new THREE.Mesh(singleGeometry_1, material_k1);

meshes[i].updateMatrix();
singleGeometry_1.merge(meshes[i].geometry, meshes[i].matrix);

mesh_1.updateMatrix();
singleGeometry_1.verticesNeedUpdate = true;
singleGeometry_1.elementsNeedUpdate = true;
mesh_1 = new THREE.Mesh(singleGeometry_1, material_k1);



What else might be the problem? I'm really wondering especially since it only seems to be not working with my custom mesh.

I just found the problem myself after trying everything for a long time. My code was fine except for one line which was missing.

After adding

mesh_1.geometry.computeBoundingSphere();

my code worked as expected.

Seems like the bounding sphere is also needed for raycasting.
Thanks for your help. Hopefully this helps anyone with the same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM