Is it possible for a Three.js raycaster to detect an intersection with a group of

I am trying to determine if my raycaster is looking at a loaded OBJ. The OBJ seems to be a THREE.Group with 3 children, not a THREE.Object as expected from Cinema4D exports. Can I modify the raycaster code to target this group instead of an object?

raycaster.set(controls.getObject().position, controls.getDirection(), 0, 40)

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

     if (intersects.length > 0) {
      //DETECTING AN INTERSECTION
      for (var i = 0; i < onOffCubes.length; i++) {
      //Check if the first intersection is with one of my cubes
        if (intersects[0].object == onOffCubes[i]) {
                ExperiencesData[i].userClose = true
            }
         }
       }

The array onOffCubes contains 6 OBJs/THREE.js Groups:

https://i.sstatic.net/MwAcr.png

When console.log(onOffCubes[0]) is executed, it returns: https://i.sstatic.net/tlhk0.png

Answer №1

Almost there. The intersect object is contained within a mesh, with the group being its parent. Make sure to compare the parent object of the intersect rather than the object itself. This means:

intersects[ 0 ].object.parent === onOffCubes[ i ]

is correct while this comparison is not:

intersects[ 0 ].object === onOffCubes[ i ]

In essence,

To simulate a similar scenario, I created six sets of three meshes each grouped together, sharing identical material. Note that onOffCubes does not represent a THREE.js group but an array of groups. This mirrors the setup in the original post's onOffCubes:

var onOffCubes = []
for ( var i = 0; i < 6; i++ ) {
    var material = new THREE.MeshBasicMaterial({ color: 0xee55aa })
    var group = new THREE.Group()
    for ( var j = 0; j < 3; j++ ) {
        var mesh = new THREE.Mesh( geometry, material );
        mesh.position.x = Math.random() * 100 - 50;
        mesh.position.y = Math.random() * 100 - 50;
        mesh.position.z = Math.random() * 200 - 200;
        group.add( mesh );
    }
    onOffCubes.push( group )
    scene.add( group )
}

Examine full scene data

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

or specifically check onOffCubes only

var intersects = raycaster.intersectObjects( onOffCubes, true );

The modified code parallels the original poster's implementation with one essential correction:

if (intersects.length > 0) {
    for (var i = 0; i < onOffCubes.length; i++) { 
        if (intersects[ 0 ].object.parent === onOffCubes[ i ]) {
            // Tested
            //intersects[ 0 ].object.material.color.set( 0xff0000 )
            // Provided code
            ExperiencesData[i].userClose = true
        }
    }
}

Answer №2

When exploring your group, make sure to check its children:

var intersections = raycaster.intersectObjects(YOUR_OBJECT.children, true);

It's worth noting that THREE.Group is a subclass of THREE.Object3D, so this approach should suffice

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

Tips for adjusting the div style when resizing the browser

As I work on a script, I encounter an issue where the style of a div should change when it becomes larger due to resizing. Even though I have come up with a solution for this problem, there are still some inconsistencies. Sometimes the width is reported a ...

Incorporating an external JavaScript or CSS file into a Java web application at runtime

I am looking to dynamically add an external JavaScript or CSS file in my test.html file. Although I am aware of a trick that involves using jQuery like this: $(”).appendTo(‘head’).attr({ rel: ‘stylesheet’, type: ‘text/css’, href: ‘**ht ...

Is it possible that data scraping with puppeteer consistently retrieves information solely from the initial page?

I'm facing an issue while trying to extract data from a website using puppeteer. Whenever I make a request for data, it always returns the information from the first page, even if I specify a different URL. Strangely, when I manually search for the sa ...

The functionality of XMLHttpRequest becomes unreliable when dealing with GET parameters

I'm attempting to retrieve the DOM of a specific page. var req = new XMLHttpRequest(); req.open( 'GET', '/sport-hobby-kultura?adListing-visualPaginator-page=2&adListing-url=sport-hobby-kultura&do=adListing-visualPaginator-showP ...

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...

Contrast the differences between arrays and inserting data into specific index positions

In this scenario, I have two arrays structured as follows: arr1=[{room_no:1,bed_no:'1A'}, {room_no:1,bed_no:'1B'}, {room_no:2,bed_no:'2A'}, {room_no:3,bed_no:'3A'}, {room_no:3,bed_no:'3B ...

Utilize jQuery UI autocomplete feature to display existing data options without the need to begin typing

By default, the behavior of the jQuery UI autocomplete is for the input field to be empty and start listing data as the user begins typing, even if the minLength is set to 0. I would like all the data to be displayed in a dropdown right from the beginning ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...

Error thrown: Uncaught TypeError - Attempted to access 'params' property of undefined object in the context of StudentDetails

I've encountered an issue where I need to transfer student application data from my server-side to my client-side. Whenever a new student application is created, I want to display their information on my StudentDetails.jsx file. Here is my Server.js c ...

Issue with React Native and Redux: Prop values are updating without being called

I'm currently facing a problem with React Native and Redux integration. Using a Redux state to toggle a modal visibility between components seems like the most efficient solution due to its cross-component nature. The modal opens and closes as expec ...

Download multiple Highcharts graphs on a single page

When using Highchart Export, I am currently able to download multiple graphs in a single page PDF. However, I would like the first graph to be on the first page and the second graph on the second page when saving as a PDF. You can find the code in the fol ...

Having trouble with toggling/display functionality in Javascript on my mobile device

I encountered an issue while using a script to toggle a div on click. Strangely, the content of the div failed to display properly on mobile devices such as Android and iOS. Despite my attempts to troubleshoot the problem, I was unable to identify the caus ...

What is the most effective method for incorporating keyframes using JavaScript in a dynamic way?

Is there a way to animate an HTML element by using a variable with keyframes, but without directly manipulating the DOM? Below is the HTML code: <div class="pawn" id="pawn1"></div> Here is the CSS keyframes code: @keyframe ...

utilizing React.js, learn how to extract the most recent user input and store it within an array

My Input component generates input tags dynamically based on JSON data. I've implemented the onChange method in the input tag, which triggers a function called "handleChange" using contextAPI to record the values in another component. The issue aris ...

Achieving optimal performance with scoped CSS in Vue.js

As I work on creating a new app using VueJs, I have noticed the implementation of "css scoped" as shown below: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> ...

ES6 syntax does not allow for exporting routers

Looking to convert NodeJS modules (constant xxx = require('yyy')) into ES6 format, but encountering errors when exporting the router using the export syntax in ES6: throw new TypeError('Router.use() requires a middleware function but ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

Using numerous WebGL models within a single webpage

In the research lab where I work, we are currently developing a webpage that will showcase a long list of 3D models that can be scrolled through, totaling around 50 models. Originally, we planned to achieve this by using separate THREE.js WebGL contexts. H ...

SimpleModal Jquery experiencing intermittent flashing in Firefox

While utilizing the SimpleModal plugin for jQuery, I've encountered an unusual issue specific to Firefox (other browsers such as Chrome, Safari, Opera, and IE are working perfectly). The problem arises when I click on the button that triggers the mod ...

Troubleshooting problems with timezones in Mongodb when filtering records based on

My goal is to retrieve all records with a "date" field falling between the startDate and endDate parameters. Here is the query I am using to fetch records from the beginning of the month up to today: var startDate = new Date(2017, 09, 1); var endDa ...