Raycaster in Three.js fails to detect objects in the scene mesh

Currently working with three.js r67 on Chrome Version 35.0.1916.153 m

I am trying to intersect some custom meshes I created in my scene, but the raycaster doesn't seem to be detecting them even though they are present in scene.children.

Here is my mesh creation code:


if (modelVertices != null && modelVertices.length >= 3) {
            triangles = THREE.Shape.Utils.triangulateShape( modelVertices, holes );

            for( var i = 0; i < triangles.length; i++ ){

               modelGeometry.faces.push( new THREE.Face3( triangles[i][0], triangles[i][1], triangles[i][2] ));

                }

            modelGeometry.computeFaceNormals();
            var modelMesh = new THREE.Mesh(modelGeometry, material);
            modelMesh.material.side = THREE.DoubleSide;
            polyhedralzGroup.add(modelMesh)
    }

Raycasting code:


var projector = new THREE.Projector();
projector.unprojectVector( vector, camera );

var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );


var intersects = raycaster.intersectObjects( scene.children, true );
helper.position.set( 0, 0, 0 );

if (intersects.length > 0 ) {  
    if (intersects[ 0 ].face != null) {
        helper.lookAt( intersects[ 0 ].face.normal );
        helper.position.copy( intersects[ 0 ].point ); 
}

It's worth noting that although computeFaceNormals() is used, it doesn't seem to be the issue (source). Interestingly, the scene does intersect other geometries made up of simple triangles without any issues. This rules out canvas offset as a problem and upon inspection, both types of geometries appear to be similar.

Any thoughts on what might be causing this issue?

Answer №1

The problem arose from the way the vertices were originally constructed using strings in three.js. While it is possible to create vertices, geometry, and meshes with string values and visualize them, these vertices cannot be used for raycasting. Simply put, the issue can be narrowed down to:

replacing this:

aVertex = new THREE.Vector3( part[0], part[1] , part[2] );

with this:

aVertex = new THREE.Vector3( parseFloat(part[0]), parseFloat(part[1]) , parseFloat(part[2]) );

It's unclear whether this behavior is intentional or a bug, as using string format for vertices does not throw errors, yet prevents raycasting on objects with string vertex geometries (potentially due to issues with computing normals).

Answer №2

One issue you may be facing is that you are passing the scene.children array directly to the raycaster.

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

Here are a couple of solutions:

Solution 1: Load your model into an object

var objects = [];

objects.push(mesh);

and then

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

Solution 2:

Place your object in a separate scene and pass that scene to your raycaster

var scene_2

scene_2 = new THREE.Scene();
scene.add(scene_2);
scene_2.add(mesh);

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

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

Restrict date range in Bootstrap Datepicker based on database values

Is there a way to remove specific date ranges from the database? For instance, if I have date ranges from 15.01.2021 to 21.01.2021 and from 24.01.2021 to 03.02.2021, is it possible to prevent these dates from being selected in the datepicker? I would lik ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

javascript identifying a variable within location.href

Within my JavaScript code, there is a variable that holds a value: var selectedItemId = null; // the value is assigned by another function Next, there is a function defined like this: function editLink() { location.href = /*[[@{/supplycontracts/edit ...

What is the significance of using sortBy in ng-click?

Recently, I've been delving into AgularJS and took on a practice exercise: JS file: function CustomersController() { this.sortBy = 'name'; this.reverse = false; this.customers= [{joined: '2000-12-02', name:'Joh ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Instructions for using jQuery to replace the final <a> tag within a specific section

Here is a section that I am working with: <section class="breadCrumb"> <a href="/">Home</a> <span class="divider">&gt;</span> <a class="CMSBreadCrumbsLink" href="/SCCU.Stg/Events-Calendar.aspx">Events Calendar ...

Create a box filled with smoke using three.js

Not long ago, I came across this interesting piece of code on CodePen that simulates smoke: https://codepen.io/teolitto/pen/KwOVvL In the code, each particle is individually added to the scene. I wanted to group all the particles together in a parent me ...

Simulating a winston logger in jest testing

I am pondering how to create mock transports for the File module within the Winston node package. While utilizing Jest, the __mocks__/winston.ts file is automatically loaded. My dilemma lies in the fact that I am unable to mock it due to the presence of th ...

Show only the objects in a MongoDB collection that have a matching status in another collection

I have two different collections - one called competition and the other called product. The competition collection contains the objectID of the product, while the product collection contains the competition_status. My goal is to only display the competiti ...

Send properties to the makeStyles function and apply them in the CSS shorthand property of Material UI

When working with a button component, I pass props to customize its appearance: const StoreButton = ({ storeColor }) => { const borderBottom = `solid 3px ${storeColor}`; const classes = useStyles({ borderBottom }); return ( <Button varian ...

Trouble Logging In: Twitter's Authentication Failure Message

When attempting to update or post a status on Twitter using Ionic, I encounter an issue. The OAuth authentication works successfully for retrieving the UserProfile Api. However, when trying to post an image or status, an error is displayed ("Could not au ...

Can the DOM be automatically refreshed after a set period of time without requiring any user input or triggers?

Is it possible to refresh the DOM using a function within a timeout without requiring an event trigger, such as a click? I have divs being inserted by Javascript that I cannot modify, and I need to loop through all of them with a specific class in order t ...

Conceal tab content by clicking outside of the tab or its contents

Here is an example of how Elementor tab works. When you click on a tab, the content section appears. I want to be able to close the content section by clicking on any other part of the page, except for the tabs and tab content themselves. This should not a ...

The combination of Material UI custom TextField and Yup does not seem to be functioning properly

I am facing an issue with integrating my custom TextField into my RegisterForm along with Yup validation. Whenever I use the custom TextField, I encounter a message "⚠ Champ obligatoire" after clicking on Submit, which is not the case when using a simple ...

The Jquery Object #<Object> does not have the 'getElement' method available

I've been attempting to set up this table, following the instructions here: Despite verifying that my browser is correctly pulling the CSS and .js files, I keep encountering an error related to my sortabletable.js file. (screenshot of the error) htt ...

What is the process for displaying a hidden div using a button?

I'm running into a problem with my project. Here is the code I've been using to hide my div element : @keyframes hideAnimation { to { visibility: hidden; } } To trigger the animation and hide the div after 6 seconds, I have implemented ...

The challenge of customizing card styling in conditional rendering with React Native

There are two primary components in this setup: homeScreen.js (the parent component) Card.js (the child component) The card component is rendered when the search is not toggled, and all necessary data is passed down as props without any rendering is ...

Optimal method for delivering static JavaScript from a node module's "dist" directory with Next.js

Currently, I am working on an application that utilizes Tesseract (OCR) to extract text from images. I am interested in making some JS files from node_modules/tesseract.js/dist downloadable directly in the browser. While I can simply copy the files to ./ ...

When executing multiple promises in parallel, the function Promise.all() does not support the spread() method

I'm attempting to simultaneously run two promises using sequelize, and then display the results in a .ejs template. However, I keep encountering the following error: Promise.all(...).spread is not a function Below is my code snippet: var environme ...

Using React to pass a link into a reusable component

I am currently utilizing a reusable component in React where I pass mostly text and some props. One of the texts requires a linked word, but I am unsure how to embed that link within a string. Any suggestions on how to pass a string with embedded links? Th ...