I've been attempting to raycast the mouse from my camera in order to trigger hover and click events on meshes within my scene.
The issue I'm facing is that my camera is currently a child object of another mesh (to facilitate easier camera movement/rotation) and as a result, my raycasting is not functioning properly. I suspect this is due to the fact that the camera is now a child of the mesh rather than directly part of the scene.
Here's a snippet of my code:
// Setting up the camera
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); // Adding camera as a child of cameraTarget
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)
}
}
My raycasting was working perfectly fine before I nested the camera under the cameraTarget object. How can I adjust my code to properly raycast from the camera despite it being a child of cameraTarget?