Raycaster无法检测到多维数据集

问题描述

如何将正方形和矩形组合成Raycaster可以成功检测到的一个对象?

我创建了一个自定义的“ Tree”对象,方法是制作一个“ Trunk”(只是一个长矩形),然后在该Trunk的顶部粘贴一个Square对象。 然后,我将该树“植入”到球体的顶部,并且试图让raycaster对其进行检测。 它不起作用。

这是我的代码:

// My custom “Tree” Object:
var Tree = function(treeColor) {
    this.mesh = new THREE.Object3D();
    this.mesh.name = "tree";

    // I start with the TRUNK - which is just an elongated Cube - meaning a Rectangle:
    var trunkGeometry = new THREE.CubeGeometry(0.2,0.5,0.2);
    var trunkMaterial = new THREE.MeshBasicMaterial({ color: "blue",wireframe: false });
    var treeTrunk = new THREE.Mesh(trunkGeometry,trunkMaterial);
    treeTrunk.position.set(0,0);
    treeTrunk.rotation.x = -Math.PI * 0.5;
    this.mesh.add(treeTrunk);

    // Then I create the FOLIAGE - which is just a regular Cube:
    var foliageGeometry = new THREE.CubeGeometry(0.5,0.5);
    var foliageMaterial = new THREE.MeshBasicMaterial({ color: treeColor,wireframe: false });
    var treeFoliage = new THREE.Mesh(foliageGeometry,foliageMaterial);
    treeFoliage.position.set(0,0);

    // And then I attach/add the FOLIAGE to the TRUNK:
    treeTrunk.add(treeFoliage);
}



// Next I make a basic Sphere:
theSun = new THREE.Mesh(new THREE.SphereGeometry(3,32,24),new THREE.MeshBasicMaterial( {color: "white",wireframe: false} ));
scene.add(theSun);


// And then I make a Tree and add it to my Sphere (`theSun`):
var oneTree = new Tree("red");
let rx = Math.random() * Math.PI * 2;
let ry = Math.random() * Math.PI;
oneTree.mesh.position.setFromSphericalCoords(3.2,ry,rx);
oneTree.mesh.lookAt(theSun.position);
theSun.add(oneTree.mesh);

// Next I add both theSun and the Tree to my “objectsForRayCasterArray” - a global var I use in my raycaster test:
objectsForRayCasterArray.push(oneTree);
objectsForRayCasterArray.push(theSun);


// In my render() function,I do the usual raycasting business:
        rayCaster = new THREE.Raycaster();

function render() {
    requestAnimationFrame(render);

    controls.update();
    renderer.render(scene,camera);
        
    // Raycasting stuff:
    rayCaster.setFromCamera(mousePosition,camera);
     
    var intersectingObjectsArray = rayCaster.intersectObjects(objectsForRayCasterArray);
        
    if (intersectingObjectsArray.length > 0) {
        if (intersectedObject != intersectingObjectsArray[0].object) {
            console.log(“Intersected!”);
        }      
    }

注意:当我使用相同的代码而不是Tree时,我只是将常规Cube放在Sphere对象上,一切正常。 raycaster检测到Cube并触发Alert

解决方法

我最好的猜测是,由于您将treeFoliage嵌套在treeTrunk内,并且嵌套在mesh内,因此必须使用递归相交测试。

根据文档intersectObjects() accepts a second argument执行递归命中测试。这意味着它将遍历所有后代,而不仅仅是对顶级对象进行浅层检查:

rayCaster.intersectObjects(objectsForRayCasterArray,true);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...