THREE.js从儿童相机到场景的光线投射

时间:2015-03-05 07:48:53

标签: javascript camera three.js raycasting

我正在尝试从相机中对鼠标进行光线投射,以便在我的场景中对网格物体进行悬停和点击事件。

我的问题是,我的相机当前是另一个网格的子对象(为了更容易的相机移动/旋转),现在我的光线投射不起作用(我假设因为相机是网格的孩子,并且不是场景。)

这是我的代码的一部分:

//camera setup
var camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, 0.1, 1000);

var cameraTargetGeom = new THREE.SphereGeometry(0.5);
var cameraTargetMaterial = new THREE.MeshLambertMaterial({color: 0xff0000, ambient: 0xff0000});
var cameraTarget = new THREE.Mesh(cameraTargetGeom, cameraTargetMaterial);
cameraTarget.position.set(0.15, 0, 5);
scene.add(cameraTarget);
cameraTarget.add(camera);

camera.position.y = 18;
camera.rotation.x = Math.PI * -90 / 180;



// click event
renderer.domElement.addEventListener('click', clickedCanvas);

function clickedCanvas(e) {
    e.preventDefault();

    mouse.x = (e.clientX / renderer.domElement.width) * 2 - 1;
    mouse.y = -(e.clientY / renderer.domElement.height) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(scene.children, true);
    console.log(intersects);

    if (intersects.length > 0) {
        >... (redacted code)
    }
}

在将相机添加到cameraTarget对象之前,它工作正常。现在,如果它是cameraTarget的孩子,我如何从相机进行光线投射?

1 个答案:

答案 0 :(得分:8)

您可以使用以下模式进行光线投射,即使相机是另一个对象的子项,它也能正常工作。它适用于透视和正交相机。

var raycaster = new THREE.Raycaster(); // create once and reuse
var mouse = new THREE.Vector2(); // create once and reuse

...

mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

raycaster.setFromCamera( mouse, camera );

var intersects = raycaster.intersectObjects( objects, recursiveFlag );

three.js r.84