gpt4 book ai didi

three.js - Raycaster.intersectObjects() 不返回任何内容?

转载 作者:行者123 更新时间:2023-12-02 21:32:43 26 4
gpt4 key购买 nike

我的场景设置如下:

document.addEventListener('mousedown', onDocumentMouseDown, false);

var container = document.getElementById("myCanvas");

scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth*0.99, window.innerHeight*0.99 );
container.appendChild( renderer.domElement );

room_material = new THREE.MeshBasicMaterial({color: 0x00ff00});
room_material.side = THREE.DoubleSide;

objects = [];

camera.position.z = 19;
camera.position.x = 5;
camera.position.y = 30;

我有一个对象数组,我试图检测它们是否与点击相交,定义如下:

var thing0 = new THREE.Shape();
thing0.moveTo(-12.1321728566, 35.3935535858);
thing0.lineTo(7.10021556487,35.3935535858);
thing0.lineTo(7.10021556487,19.7039735578);
thing0.lineTo(5.12636517425,19.7166264449);
thing0.lineTo(5.12636517425,33.6221493891);
thing0.lineTo(-12.1377356984,33.6439534769);
var thing0Geom = new THREE.ShapeGeometry(thing0);
var thing0Mesh = new THREE.Mesh( thing0Geom, room_material );
thing0Mesh.name = "abcd";
scene.add(thing0Mesh);
objects.push(thing0Mesh);

然后我使用以下代码渲染场景:

renderer.render(scene, camera);
requestAnimationFrame(render);

最后,我对鼠标单击事件使用以下代码:

function onDocumentMouseDown(event) {
var vector = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1, -( event.clientY / window.innerHeight ) * 2 + 1, 0.5);
vector = vector.unproject(camera);
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(objects, true);
alert("well, you clicked!");
if (intersects.length > 0) {
alert("wow, it worked");
}
}

但是,无论我做什么,当警报跟随在 raycaster.intersectObjects(objects, true); 后面时,它都不会被调用。但是,当它放置在它之前的任何位置时,它确实会被调用。在这种情况下, raycaster.intersectObjects(objects, true); 似乎有点黑洞?

我认为我的设置有问题?任何帮助将不胜感激!

最佳答案

我尝试过以下两件事并取得了成功:

1) 如果您的网格面未指向光线原点,请确保您使用的是 Three.DoubleSide。这直接来自documentation :

“请注意,对于网格体,面必须指向射线的原点才能被检测到;穿过面背面的射线的交点将不会被检测到。要针对对象的两个面进行射线转换,您需要将 Material 的 side 属性设置为 THREE.DoubleSide。”

2) 在光线转换之前使用 mesh.updateMatrixWorld()。这来自另一个 stackoverflow 帖子:threejs raycasting does not work

mesh.updateMatrixWorld(); // add this

raycaster.set(from, direction);

关于three.js - Raycaster.intersectObjects() 不返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31072742/

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