Using THREE.js to cast rays from a secondary camera onto the scene

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?

Answer №1

If you want to implement raycasting, you can follow this pattern which will function correctly even when the camera is attached to another object. It is compatible with both perspective and orthographic cameras.

const raycaster = new THREE.Raycaster(); // initialize once for reuse
const mouse = new THREE.Vector2(); // initialize once for reuse

...

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

raycaster.setFromCamera( mouse, camera );

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

This code snippet is specific to three.js version r.84

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript does not generate any errors when indexing an object with brackets

One interesting thing I've noticed about TypeScript is that it allows me to use bracket notation to access an object via index, even when it only has keys. For example: interface testObject { name: string; id: number; } let first: testObject ...

Attempting to transmit information to database using AJAX in the context of CodeIgniter

I'm having some trouble with my AJAX setup. It doesn't seem to be posting any data to the database, despite trying various solutions I found online. That's why I've turned to this platform for help. When testing in Postman and sending ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

What is the reason that the slick slider is unable to remove the class filter?

Having troubles with my slickUnfilter function, even though slickFilter is working perfectly? Here's a snippet of my HTML: <div class="slider-wrapper" id="wrapper"> <div class="post" id="post1"&g ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

Is there a way to display a different file, such as index.html, based on the screen width?

I'm facing an issue. I have completed a web page (with HTML, CSS, and JavaScript), but now I want to create a mobile version using different HTML files, another index.html file, and a separate CSS file. What changes do I need to make in the main page ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Sorting items in backbone.js can be achieved by using the sortBy method

Currently, I am delving into learning backbone.js and have decided to create my own Todo application using backbone.js along with a local storage plugin. At this point, I have successfully developed the Todo app where you can add and remove tasks. However, ...

tips for accessing dynamic key pair value data in Angular

I am facing an issue where I cannot retrieve the dynamic key pair value from the dynamic JSON. Below is my JSON: var d = { "pexels-photo.jpeg": { "information": "laptop", "desc": { "mimetype": "image/jpeg", "id" ...

Tips for choosing an option in a form using Selenium with JavaScript

I am currently in the process of automating some tests for a specific form, and I have successfully automated all steps except for selecting an option from a dropdown menu using JavaScript. Here is my code: const {Builder, By, Key} = require("sel ...

I'm curious about something I noticed in an HTML example within the text content section of elements. Can you help clarify this for me?

I recently came across a repository that was part of a bootcamp curriculum for learning full stack development. In one of the lessons on jQuery, students were tasked with building a calculator. However, I noticed some strange variables in the HTML where te ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Knockout.js dropdown pre-selection in nested JavaScript objects is functioning smoothly in KO 2x versions, but there seems to be a compatibility issue with KO 3x versions

This is a sample data that will be loaded from the server in JSON format and constructed into the below object graph. It consists of an array of "Choice" objects, each with properties like id, name, stages, & currentStageId. The "stages" property in th ...

Is there a more efficient alternative to the sluggish scroll event?

Currently, I have set up a scroll event that tracks the user's position on the page and updates the navigation styling based on which section they are viewing. However, the calculation I'm using during scrolling is quite resource-intensive and ca ...

Improving file reading and parsing efficiency with fast random access using csv-parse in Node.js

I recently encountered a challenge while working with the csv-parser library in node for parsing large CSV files. The files I work with can range from 50,000 to 500,000 lines or even larger. My task involved performing computations on this data and then su ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...