gpt4 book ai didi

three.js - Raycaster 无法检测到立方体

转载 作者:行者123 更新时间:2023-12-04 08:59:39 36 4
gpt4 key购买 nike

你如何将一个正方形和一个矩形组合成一个 Raycaster 的对象能检测成功吗?
我通过制作一个“树干”(只是一个长矩形)来创建一个自定义的“树”对象,然后在该树干顶部粘贴一个方形对象。
然后我将那棵树“种植”在一个球体的顶部,我正试图获得我的 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, 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, 0.5);
var foliageMaterial = new THREE.MeshBasicMaterial({ color: treeColor, wireframe: false });
var treeFoliage = new THREE.Mesh(foliageGeometry, foliageMaterial);
treeFoliage.position.set(0, 0.5, 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 .

最佳答案

我最好的猜测是,因为您正在嵌套 treeFoliagetreeTrunk ,以及里面的 mesh ,您将不得不使用递归交叉测试。
根据文档, intersectObjects() accepts a second argument执行递归 HitTest 。这意味着它将遍历所有后代,而不仅仅是对顶级对象进行浅层检查:rayCaster.intersectObjects(objectsForRayCasterArray, true);

关于three.js - Raycaster 无法检测到立方体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63626849/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com