Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the right direction. Here is the snippet of code for my onCanvasMouseDown function:

        event.preventDefault();
        mouse.x = ( (event.clientX - renderer.domElement.offsetLeft) / renderer.domElement.width ) * 2 - 1;
        mouse.y = - ( (event.clientY - renderer.domElement.offsetTop) / renderer.domElement.height ) * 2 + 1;
        mouse.z = 0.5;

        projector.unprojectVector( mouse, camera);
        raycaster.setFromCamera( mouse, camera);

        var intersects = raycaster.intersectObjects( scene.children );

        if( intersects.length > 0 ) {
            intersects.map(function(d) {
                if(d.object.name === "sphere") {
                           //etc...
                }
            })

        }

However, I am encountering an issue where intersects consistently returns empty. I suspect that the problem may be related to how I am setting up the mouse coordinates, but I am uncertain about how to address it.

EDIT: I have observed that I am able to detect a sphere when I rotate the plot to view it from above, but I need to be able to detect it regardless of the rotation. Does this provide any specific insights?

Answer №1

If your elements (dots) are part of a THREE.Group(), that is a subordinate of the scene, then

var hits = raycaster.intersectObjects( scene.children );

may result in a negative intersection.

To target the children of the group, it is advisable to use

var hits = raycaster.intersectObjects( scene.children, true );

Alternatively, you can opt for a different approach: place the elements you wish to test for intersection in an array and then pass that array to the intersectObjects method.

var elements = [];
for(i=0; i<10; i++){
    ...
    var meshobj = new THREE.Mesh(...);
    scene.add(meshobj); // or group.add(meshobj);
    elements.push(meshobj);
}

...

var hits = raycaster.intersectObjects( elements ); // in this case, you do not need the recursive parameter, as you have the array with the elements you actually want to test for intersection

Answer №2

For those with an offset, it is recommended to utilize the boundingRect method.

var rect = renderer.domElement.getBoundingClientRect();
mouse.x = ( ( event.clientX - rect.left ) / ( rect.width - rect.left ) ) * 2 - 1;
mouse.y = - ( ( event.clientY - rect.top ) / ( rect.bottom - rect.top) ) * 2 + 1;

To see a demonstration, check out the demo of this solution.

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

inability to conceal a two-dimensional marker array within Google Maps API v3

I need some help with my marker that refuses to hide Even after using setMap, my marker is still visible on the map Here is the error message from the console Please assist! Thank you in advance markers[i][j].setMap(null); markers.setMap(null); va ...

JavaScript code to dynamically change the minimum value of an input field when the page

How can I use JavaScript to change the minimum value onload? I tried the following code but it didn't work: <script type="text/javascript">$(document).ready(function(){ $("#quantity_5c27c535d66fc").min('10'); });</script> ...

The AJAX Request has indicated that the entity provided is not in an accurate 'application/json' format. It seems to be missing or empty, leading to an error with a code of '400'

While attempting to create an AJAX request to submit users to an external API, I faced a problem that is hindering my progress. Since I'm more familiar with PHP than JS, I saw this as an opportunity to expand my knowledge in JavaScript. The approach ...

Tips for organizing a Material UI DataGrid table effectively while keeping the total sum rows within the DataGrid unaffected

Check out my codeSandbox link here: https://codesandbox.io/s/making-sum-of-column-in-datagrid-mui-zjzfq6?file=/demo.js I've noticed that when I sort by ascending, the subtotal, total, and tax rows move up, but when I sort by descending, they move dow ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

The Vue/Vuetify wrapper component does not automatically pass on the `hide-details` parameter to the input component

I recently crafted a custom wrapper for the v-select input using Vuetify. Along with custom properties, I utilized the v-bind="$props"attribute to inherit all props. Upon testing, I observed that while this method applies to most props, it doesn ...

JavaScript library error: "Uncaught ReferenceError: numjs is undefined"

Hi there! I've recently started learning JavaScript and am currently exploring the functionalities of NumJS. However, I've encountered an error that's got me stumped. Even though the file "numjs.js" is included locally within the HTML, I kee ...

Combine less files in webpack to generate a single minified CSS output file

Can webpack be used to combine multiple less files into one minified CSS file? I'm having trouble setting different output paths for my files. How can I make my CSS file output to './assets/stylesheets/bundle/' instead of './assets/ja ...

Transfer the updated variable from a static JavaScript file to Next.js

I am facing a challenge with a conditional render in my component. I am unable to display the value of a variable. In one file, I have all my functions that I export in index.js import FunctionServices from "../services/functionServices" export ...

Unchecking random checkboxes within a div using jQuery after checking them all

Once a link is clicked on, all checkboxes within that particular div will be checked. function initSelectAll() { $("form").find("a.selectAll").click(function() { var cb = $(this).closest("div").find("input[type=checkbox]"); cb.not(":checked" ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

jQuery dropdown menu button impacts the entire webpage

I created this jQuery code to modify the drop menu elements, but it ended up affecting the entire page. How can I resolve this issue? $(".dropmenuac").on("click",function(){ $(".dropmenulist").css("opacity",& ...

Oops! A JSON parsing error occurred due to the presence of an unexpected token '}'

I encountered an issue while trying to develop a registration route using passportjs. When sending a request via Postman, I received the following error message: SyntaxError: Unexpected token } in JSON at position 119    at JS ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

discord.js fails to provide a response

const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Clien ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

Display the checkbox as selected using AngularJS

I have already submitted a form with a checkbox value. Now, I am trying to display the checkbox as "checked" using AngularJS based on the value retrieved from the data source. Can someone guide me on how to achieve this? ...

The functionality of passing POST variables to the model seems to be malfunctioning in PHP CodeIgniter when attempting to use the

I attempted the code snippet below: function doAjax() { var sList = ""; $('input[type=checkbox]').each(function () { var sThisVal = (this.checked ? "1" : "0"); ...

Organizing content by title or link using jQuery

I am attempting to organize a list based on the title of a link so that it is displayed in an A-Z format. Unfortunately, I am unable to modify the HTML structure easily for better styling as I am restricted to using tr>tr>tr>. I am struggling to f ...