THREE.js 从儿童相机到场景的光线投射 [英] THREE.js Raycasting from a child camera to the scene

查看:22
本文介绍了THREE.js 从儿童相机到场景的光线投射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的相机对鼠标进行光线投射,以在我的场景中的网格上执行一些悬停和点击事件.

I am trying to raycast the mouse from my camera to do some hover and click events on meshes in my scene.

我的问题是,我的相机目前是另一个网格的子对象(为了更方便的相机移动/旋转),现在我的光线投射不起作用(我假设是因为相机是网格的子对象,而不是场景).

My problem is, that my camera is currently the child object of another mesh (for easier camera movement/rotation) and now my raycasting doesn't work (I assume because the camera is a child of the mesh, and not the scene).

这是我的代码的一部分:

This is parts of my code:

//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 的孩子,我如何从相机进行光线投射?

It was working fine before I added the camera to the cameraTarget object. How can I raycast from the camera now that it is a child of the cameraTarget?

推荐答案

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

You can use the following pattern for raycasting, and it will work correctly even if the camera is the child of another object. It works for both perspective and orthographic cameras.

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

three.js r.84

这篇关于THREE.js 从儿童相机到场景的光线投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆