简体   繁体   English

Three.JS - 自定义网格上的光线投射

[英]Three.JS - Raycasting on custom mesh


I'm currently trying to raycast a custom created mesh in three.js.我目前正在尝试在 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).在研究了很长一段时间后,我发现了一些自定义光线投射的典型问题并尝试修复它们(updateMatrixWorld,双面材料,... - 请参见下面的代码)。

I'm using the following function for my raycasting:我正在使用以下 function 进行光线投射:

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.希望这可以帮助任何有同样问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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