javascript – Three.js raycaster交集
作者:互联网
我编写了下面的代码来获得与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");}
如果我检查相交[0].点我只能看到立方体相交的最远点面而不是第一个(例如,如果你看到前面的立方体并制作一条光线,这条光线在与第一张面相交之前并在第一张脸后面的第二张脸后面.)
此代码的目标是仅在单击顶点时创建事件.
所以在此之后我编写了代码来计算点击点和所有顶点的欧氏距离
并返回最接近点击的顶点.
如果您有其他想法只有在点击顶点时才能触发事件.
解决方法:
是的,光线投射的基本思想是我们投射垂直于平面的光线,我们找到光线相交的物体列表.
因此,要访问第一个元素,您只需添加以下代码即可.
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,three-js,raycasting 来源: https://codeday.me/bug/20190830/1767968.html