Using Three.JS to implement raycasting on a custom mesh


I've been tackling an issue with raycasting a custom mesh in three.js. Surprisingly, while raycasting works flawlessly on some imported meshes, it just doesn't seem to cooperate at all with my custom mesh.

After extensive research, I came across common problems associated with custom raycasting and attempted various solutions (such as updateMatrixWorld, double side material, etc. - refer to the code snippet below).

This is the function I'm using for raycasting:

mouse.x = ((e.clientX - container.offsetLeft) / container.clientWidth) * 2 - 1;
mouse.y = -((e.clientY - container.offsetTop) / container.clientHeight) * 2 + 1;

rayCaster.setFromCamera(mouse, camera);
var intersect = rayCaster.intersectObjects(scene.getObjectByName('loaded_object').children, true); // functioning properly


mesh_1.geometry.computeFaceNormals();
mesh_1.updateMatrixWorld();
var intersect_custom = rayCaster.intersectObjects([mesh_1], true); // not yielding results

While the first intersection behaves as expected, the custom intersect fails completely - consistently returning an empty array.
Could it be that the issue lies within my custom mesh?

This is how I constructed my custom mesh:

material_k1.side = THREE.DoubleSide;
var singleGeometry_1 = new THREE.Geometry();
var mesh_1 = new THREE.Mesh(singleGeometry_1, material_k1);

meshes[i].updateMatrix();
singleGeometry_1.merge(meshes[i].geometry, meshes[i].matrix);

mesh_1.updateMatrix();
singleGeometry_1.verticesNeedUpdate = true;
singleGeometry_1.elementsNeedUpdate = true;
mesh_1 = new THREE.Mesh(singleGeometry_1, material_k1);



What else could possibly be causing this issue? It's perplexing, especially considering that it only seems to be problematic with my custom mesh.

Answer №1

Hours of troubleshooting led me to discover the root cause on my own. Everything in my code seemed correct except for a crucial missing line.

Once I included

mesh_1.geometry.computeBoundingSphere();

my code finally performed as intended.

It appears that the bounding sphere is essential for raycasting functionality.
Thank you for your assistance! Hopefully, this solution aids others facing a similar issue.

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

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

Adding a background image in javascript using data from a MySQL database

My current tech stack includes CodeIgniter, vanilla JavaScript, AJAX, CSS, and MySQL. I am trying to figure out how to set the background of an image that is stored in a MySQL database. While the following code is error-free and working perfectly, my cha ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

Disable the ng-change event

Is there a way to prevent the ng-change event from happening? I have a select box with an option that I don't want users to select. Instead, I want to display a warning message and then revert back to the previously selected option. To achieve this, ...

The ReferenceArrayInput request is lacking an api-prefix

I have been attempting to utilize the ReferenceArrayInput component from react-admin in order to modify a OneToMany relationship. Although the options for the multi-select input load correctly, the actual selection does not work as expected. Interesting ...

Tips for automatically scrolling to the bottom of a div when new data is added

I'm working on a project with a table nested inside a div, and it has some unique styling: #data { overflow-x:hidden; overflow-y:visible; height:500px; } Currently, as the table fills up with data, a vertical scroll bar appears. But I wa ...

XMLHttpRequest Refusing to Send Data

This snippet of code is crucial for the custom extension: let url = "https://mywebsite.com/data.php"; function sendRequest() { var client = new XMLHttpRequest(); client.open("POST", url, true); client.setRequestHeader("Content-Type", "text/pla ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

Can transitions be applied to links in this manner?

Having an issue with ajax requests, I am currently resorting to using JavaScript linking. This is how I normally link: window.location.href = ('file:///android_asset/www/custom/kontakty.html'); I am curious if it's possible to add a transi ...

Tips for sending values via props to a different component and the common error message: "Consider using the defaultValue or value props instead of setting selected on the <option> element"

Currently, I am attempting to pass the selected value using the prop: handle state change, but encountering two errors. Error 1 : Instead of setting selected on <option>, use the defaultValue or value props. Error 2 : A property 'active' ...

Angular: Having trouble accessing method within scope

I am attempting to utilize a method from my $scope controller, which is imported from a Factory, and execute it using the onclick method in an Ionic-based HTML. However, I am encountering the issue of getting undefined and I am unsure of the reason behind ...

creating keys dynamically in a Mongoose schema using Node.js JavaScript

I consider myself an intermediate in node.js. Within my mongoose schema, I have a variety of fields listed below: result_1 result_2 result_3 result_4 result_5 The data will come in numeric form (1-5) as the result number, and based on this number, I nee ...

What is the process for customizing the default animation in the Dialog component?

Currently I am utilizing the Material UI framework and looking into modifying the default animation for a Dialog opening. Specifically, I would like the Dialog to appear from bottom to top when it opens up. Any suggestions on how this can be achieved? Ap ...

Incorporate href along with ng-click for improved functionality

I need a link that will call a $scope-function when clicked, which will then display another view. I also want the user to be able to right-click on the link and open it in a new window or bookmark it. Unfortunately, the current html code is not worki ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...

Modify data in a table using Dialog Component in Angular Material

I need to implement a Material Dialog feature that allows users to update entries in a table by clicking on the "Change Status" button. Check out this functional snippet: https://stackblitz.com/edit/angular-alu8pa I have successfully retrieved data fr ...

The xhr.upload event listener is triggered when the xhr.responseText is empty after loading

const request = new XMLHttpRequest(); request.open('put', url, false); request.upload.addEventListener('load', function(e) { alert(request.responseText); }, false); Why is the responseText property of the XMLHttpRequest object empt ...

index() jQuery function is not

Upon clicking on an element with the class 'sections', I expect to see an alert displaying its class index, however, it appears to be showing an incorrect number. For example, if I click on the first div element with the class 'sections&apo ...

Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one: var array= [ [1,"dataA","dataB","dataC","dataD"...], [2,"dataA","dataB","dataC","dataD"...], [3,"dataA","dataB","dataC","dataD"...], [4,"dataA","dataB","dataC","dataD"...]... ...

To utilize the span and input text increment functionality, simply use the required input type number and hold either the up or down arrow

Is it possible to increment the value of an input type number by 1 when holding down on a mobile device? <input type="text" id="number" value="1"> <span id="upSpan"> Up </span> $('#upSpan').on('touchstart', function ...