我编写了下面的代码来获得与 3d 形状的交点。它工作得很好,但如果有两个与形状的交点,它只会返回最远的交点,而我需要与形状最近的交点。我怎样才能找到最近的十字路口?

  /*here I create a cube*/

            var geometry0 = new THREE.Geometry()
            geometry0.vertices = [new THREE.Vector3(0.5, -0.5, 0.5), new THREE.Vector3(-0.5, -0.5, 0.5), new THREE.Vector3(-0.5, -0.5, -0.5), new THREE.Vector3(0.5, -0.5, -0.5), new THREE.Vector3(0.5, 0.5, 0.5), new THREE.Vector3(-0.5, 0.5, 0.5), new THREE.Vector3(-0.5, 0.5, -0.5), new THREE.Vector3(0.5, 0.5, -0.5)];
            geometry0.faces = [new THREE.Face3(3, 2, 1), new THREE.Face3(3, 1, 0), new THREE.Face3(4, 5, 6), new THREE.Face3(4, 6, 7), new THREE.Face3(0, 1, 5), new THREE.Face3(0, 5, 4), new THREE.Face3(1, 2, 6), new THREE.Face3(1, 6, 5), new THREE.Face3(2, 3, 7), new THREE.Face3(2, 7, 6), new THREE.Face3(3, 0, 4), new THREE.Face3(3, 4, 7)];
            geometry0.computeFaceNormals();
            geometry0.computeVertexNormals();
            var material0 = new THREE.MeshBasicMaterial({color: 0x39d2dbe7fff39d2, transparent: true, opacity: 0});
            mesh0 = new THREE.Mesh(geometry0, material0);
            egh0 = new THREE.EdgesHelper(mesh0, 0x000);
            egh0.material.linewidth = 2;
            scene.add(egh0);


            objects.push(mesh0);
            projector = new THREE.Projector();
            console.log(objects);
            mouse2D = new THREE.Vector3(0, 10000, 0.5);//controllare i valori



    /* here I create the ray */


document.addEventListener('click', onDocumentMouseClick, false);


        function onDocumentMouseClick(event) {

            event.preventDefault();

            mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse2D.y = -(event.clientY / window.innerHeight) * 2 + 1;
             var vector = new THREE.Vector3( mouse2D.x, mouse2D.y, 0.5 );

            projector.unprojectVector( vector, camera );

            var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );


            var intersects = raycaster.intersectObjects( objects );

            if (intersects.length > 0) {
                console.log("ok");}

如果我检查 intersects[0].point 我只能看到相交的立方体的最远点面而不是第一个(例如,如果你看着你面前的立方体并制作一条射线,这条射线在与第一个面相交之前在与第一个面后面的第二个面相交之后。)
此代码的目标是仅在您单击顶点时创建一个事件。
所以在这之后我写了代码来计算从点击点和所有顶点的欧几里德距离
并返回最接近点击点的顶点。
如果您有其他想法仅当您单击顶点时才触发事件是受欢迎的。

最佳答案

是的,ray casting 的基本思想是我们转换一条垂直于平面的射线,我们找出射线相交的对象列表。

因此,访问第一个元素所需要做的就是添加以下代码。

var intersects = raycaster.intersectObjects(objects);

if (intersects.length > 0) {
       var firstIntersectedObject  = intersects[0];
       // this will give you the first intersected Object if there are multiple.
    }

这是 one of my other SO post,我在其中以更详细的方式解释了一些事情,您可以引用它以更好地了解光线转换的功能。

关于javascript - 三.js raycaster 交集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26371847/

10-11 23:40