我编写了下面的代码以获得与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]。点我只能看到立方体的最远点面而不是第一个(例如,如果你看到前面的立方体并制作一条光线,这条光线在相交之前第一张脸和第二张脸在第一张脸后面。) 此代码的目标是仅在单击顶点时创建事件。 所以在此之后我编写了代码来计算点击点和所有顶点的欧氏距离 并返回最接近点击的顶点。 如果您有其他想法只有在点击顶点时才能触发事件。
答案 0 :(得分:5)
是的,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,其中我已经用更详细的方式解释了一些事情,你可以参考它来更好地理解光线投射的功能。
答案 1 :(得分:0)
尝试完成此example。查看控制台中的消息。
<script src="js/controls/EventsControls.js"></script>
EventsControls = new EventsControls( camera, renderer.domElement );
EventsControls.draggable = false;
EventsControls.onclick = function() {
console.log( this.focused.name );
console.log( 'this.focusedPoint: (' + this.focusedPoint.x + ', ' +
this.focusedPoint.y + ', ' + this.focusedPoint.z + ')' );
console.log( 'this.focusedDistance: ' + this.focusedDistance );
}
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
EventsControls.attach( mesh );
//
function render() {
EventsControls.update();
controls.update();
renderer.render(scene, camera);
}