THREE.js Raycasting from the children's camera to the stage

I'm trying to cut a mouse from a camera to hover over events on grids in my scene.

My problem is that my camera is currently a child of a different grid (to make it easier to move / rotate the camera) and now my raycasting is not working (I suppose because the camera is a child of the grid, not the scene).

This is part 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) } } 

It worked great before I added a camera to the CameraTarget object. How can I raycast from a camera now that it is a child of the camera?

+6
source share
1 answer

You can use the following template for raycasting, and it will work correctly even if the camera is a child of another object. It works for both perspective and spelling 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

+7
source

Source: https://habr.com/ru/post/983358/


All Articles