Interaction between elements in Object3D

I have a collection of objects grouped together in Object3D and I'm attempting to detect when they are clicked on. My scene has dimensions of 600x400, my camera is part of a three-object, and the code for handling events looks like this:

function onDocumentMouseDown( event ) {
   event.preventDefault();

   var mouse = {};
   mouse.x = ( event.clientX / 600 ) * 2 - 1;
   mouse.y = - ( event.clientY / 400 ) * 2 + 1;

   var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
   projector.unprojectVector( vector, three.camera );

   var ray = new THREE.Ray( three.camera.position, vector.subSelf( three.camera.position ).normalize() );

   var intersects = ray.intersectObjects( group.children );
   alert(intersects.length);
   [...]
}

Currently, I am displaying the number of intersected objects. However, it always remains at zero. It seems unable to find any intersected objects. I've experimented with adjusting the x, y, and z values of my projection vector but haven't had any success.

I have provided a simplified example illustrating this issue on jsfiddle. Perhaps someone can offer a quick insight into what might be causing this problem?

Answer №1

Your fiddle is set up to utilize

THREE.SceneUtils.createMultiMaterialObject()
, which creates a hierarchical structure. To ensure proper functionality, make sure to include the recursive flag when using ray.intersectObjects().

var intersects = ray.intersectObjects( group.children, true );

Update: The variable ray is now an instance of THREE.Raycaster rather than THREE.Ray.

Version three.js r.58

Answer №2

Dealing with a similar issue, I found the answer provided by WestLangley to be quite helpful. A great solution! If you're having trouble with selecting objects grouped within an Object3D wrapper using the mouse, here is my own approach.

To optimize performance, I started by creating an array of selectable objects. This way, the RayCaster only needs to search through the specific objects you want for selection, rather than scanning the entire scene. I then directly attached this array to the scene object (for easy accessibility throughout my application).

scene.selectable = [];

Next, I added all the individual objects that I wanted to be selectable to this array. Remember to include only meshes/sprites/etc from your group, not the entire group itself. The key line is the last one in this snippet:

var myWrapper = new THREE.Object3D();
var myObject = new THREE.Mesh( something );
myWrapper.add( myObject );
scene.add ( myWrapper );
scene.selectable.push( myObject );

Finally, in your mouse selection function, utilize the raycaster as follows:

var intersects = ray.intersectObjects( scene.selectable );

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 validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Adjust the size of the frame by dragging the mouse cursor to change both the width

I'm a bit lost on where to direct this question, so I decided to include the html, web, and css categories (though I suspect it's related to css). The task at hand involves creating an html page with a fixed header, while the content area compris ...

Incorporating Keyboard Features into Buttons

How can I toggle the page selectors in #pageList using a keyboard shortcut instead of clicking on the .togglePL button? I've tried looking up solutions online and asking questions here, but haven't found a working solution yet. Below is the code ...

Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method. While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling ...

Sending JavaScript/jQuery variables to a different PHP page and navigating to it

For a while now, I've been working on: Executing a .js file on the client side (successful). Passing the returned object (the variables returned) as an array to another php page for further processing (successful but with issues). The first point, ...

Issue with React form not appearing on web browser

I'm having trouble getting the form to show up on the browser. For some reason, the formComponentDict variable is not displaying any of the form steps. Can anyone point me in the right direction? Any assistance would be greatly appreciated. Thank you ...

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

invoking a PHP function within a JavaScript script

In my collection of essential functions, there is one that I am particularly interested in: //the functions file //........ function user_exists($username){ $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') F ...

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

The e.currentTarget attribute in Material UI buttons is a key element that

I am facing an issue with implementing three tabs and buttons in my project. Each button should display a corresponding message when selected I have tried using e.currentTarget but no success so far. Can someone guide me on how to resolve this problem? You ...

Is there a way to utilize nodemon without having to install it through npm?

I'm having trouble with my network not allowing me to use npm install. Is there another way for me to install and use nodemon? I've noticed that Node only runs after setting PATH variables on Windows. I attempted to set the path for nodemon, but ...

Encountered an issue with launching Chrome in Puppeteer for Node.js

My code was uploaded to EC2 AWS, but unfortunately it is not working properly after the upload. Interestingly, it runs correctly on localhost. Despite trying various solutions, I am still facing this issue. Any suggestions on the correct approach to resolv ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

The useEffect function is failing to execute when deploying on Vercel with Vite and React Router

After successfully deploying a React site using Vite on Vercel, with React Router for routing and a separate backend service, everything seemed to be working fine on my local machine. However, when testing the deployment on Vercel, I encountered an issue w ...

Conceal a div while revealing the other div

I am currently trying to achieve a unique visual effect. I have three divs named div1, div2, and div3. The objective is for div1 to slide up and disappear when clicked, while div2 simultaneously slides up and becomes visible. Similarly, when div2 is click ...

Select2 version 4.0.3 encountering issues when trying to automatically populate additional select2 fields with data fetched through ajax

I'm encountering an issue with Select2. Essentially, I need to populate other form fields with data retrieved from Select2's Ajax search. Even after following an example found here: Select2 4.0 - Push new entry after creation I'm still un ...

Searching and selecting columns in React using Material-UI

Currently, I am using Material-UI data tables and have implemented a search functionality similar to this Codesandbox example, which only searches the Name/Food column. This is my existing code snippet: const [filterFn, setFilterFn] = useState({ fn: items ...

What is up with this strange JavaScript variable string / DOM selection?

I'm facing a strange issue with a variable that appears to be a string when alerted, but in the console, it is actually a DOMSelection presented in tree form. How can I retrieve the actual string value from this console output? DOMSelection anchorNod ...

Summernote - When validating text, it is shown as raw HTML

I have integrated Codeigniter with Summernote on the frontend. In a form, if certain fields are left empty, the same page reloads for validation checking. The JavaScript and CodeIgniter code I am using is as follows: $(window).load(function(){ &l ...

Avoiding the backslash in JavaScript

<script type="text/javascript"> console.log(#Fileurl#); jQuery.ajax({ url: "http://xyz:8800/aaa/bbb/ccc", type:'POST', dataType: 'JSON', data:{"file":"#Fileurl#"}, success: function ...