The click detection on loaded 3DObjects using threejs raycast is not functioning properly

After loading a .obj file using the following code:

var loader = new THREE.OBJMTLLoader();
loader.load( "../obj/machine.obj", '../obj/machine.mtl',  this.loadObject);

I attempt to detect a click on it with the following code:

 click: function(event){
        this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
        this.mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
        var vector = new THREE.Vector3( this.mouse.x, this.mouse.y, 1 ).unproject( this.camera );
        this.raycaster.set( this.camera.position, vector.sub( this.camera.position ).normalize() );

        console.log(this.scene.children);
        var intersects = this.raycaster.intersectObjects( this.scene.children );

        if ( intersects.length > 0 ) {

            console.log("hitting something");

        }
    },

Even though the loaded 3DObject is visible in 'this.scene.children', the click detection only works on meshes. Here is an example of the structure of the object:

[THREE.Mesh, THREE.Line, THREE.PointLight, --> THREE.Object3D <-- ]0: THREE.Mesh__webglActive: true__webglInit: true_listeners: Object_modelViewMatrix: THREE.Matrix4_normalMatrix: THREE.Matrix3castShadow: falsechildren: Array[0]eulerOrder: (...)frustumCulled: truegeometry: THREE.IcosahedronGeometryid: 4material: THREE.MeshBasicMaterialmatrix: THREE.Matrix4matrixAutoUpdate: truematrixWorld: THREE.Matrix4matrixWorldNeedsUpdate: falsename: ""parent: THREE.Sceneposition: THREE.Vector3quaternion: THREE.QuaternionreceiveShadow: falserenderDepth: nullrotation: THREE.EulerrotationAutoUpdate: truescale: THREE.Vector3type: "Mesh"up: THREE.Vector3useQuaternion: (...)userData: Objectuuid: "46D85379-A9CE-4221-A599-39D13EE4CB34"visible: true__proto__: Object1: THREE.Line2: THREE.PointLight3: THREE.Object3D

It seems like the raycast method may need something specific for loaded 3DObjects. If anyone has any insights or ideas on what might be missing, I would greatly appreciate the help!

Answer №1

In order to achieve the desired result, it is necessary to include the recursive flag like this:

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

Compatible with three.js version r.69

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

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

The message sent by the node containing a large body (1.3 mb) encountered an error: 413 Request Entity Too Large

Using Fiddler, I am creating a POST message with a header. Content-Type: application/text-enriched app.post('/books',function(req,res){ var writeStream = fs.createWriteStream('C://Books.txt' ,{ flags : 'w' }); ...

GULP showing an error message "ACCESS DENIED"

Exploring the fascinating realm of Gulp for the first time has been quite an adventure. I have managed to create a gulpfile that effectively handles tasks like reading, writing, and compiling sass/css/js/html files. However, when I try to access the site o ...

Obtaining a phone number from a contact in Nativescript Angular: A step-by-step guide

Upon executing the following code: let desiredFields = ['display_name','phone','thumbnail','email','organization']; console.log('Loading contacts...'); let timer = new Date().getTime(); Contact ...

Is there a way in MVC3 / .net4 to convert a JSON formatted JavaScript array into a C# string array?

I am facing a challenge with my MVC3/.Net service where it is receiving arguments in the form of a JSONified Javascript array. I want to convert them into a C# array of strings. Is there a built-in solution available for this task, or do I need to create ...

What could be the reason for my directive not properly interpolating the scope variable?

I attempted to create a directive that would swap out a CSS link with an inline style definition. Check out the functional version here. Now, I am hoping to achieve the same functionality using interpolation, so that I don't have to manually set the ...

Invoking a JavaScript function within an ASP Repeater

I am looking to incorporate a JavaScript function into an ASPX page within Visual Studios 2012. This function is designed to retrieve 7 values from a database multiple times and dynamically adjust the CSS based on these values. Additionally, it targets a s ...

Generate a table framework by dynamically adjusting the number of rows and columns

I'm running into an issue with my implementation of nested for-loops to dynamically generate a table using JavaScript. For this particular scenario, let's assume numRows = 2 and numCols = 6. This is the code snippet in question: let table = $( ...

ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated! function onlyOne(checkbox) { var checkboxes = document.getElement ...

Oops! An uncaught exception error occurred because the primordials were not defined

I used npm to install the package called aws-s3-zipper, but now I am encountering an error. This is the code snippet causing the issue: AWS = require("aws-sdk"); var S3Zipper = require("aws-s3-zipper"); function zipFolderOnS3() { var zipper = new S3 ...

Is there a more efficient method for translating arrays between JavaScript and PHP?

Currently, I am in the process of developing a web page that has the capability to read, write, and modify data stored in a MySQL database. My approach involves utilizing PHP with CodeIgniter for handling queries while using JavaScript to dynamically updat ...

When attempting to render a base64 string in an <img> tag using ReactJS, an error message ERR_INVALID_URL is displayed

I am currently working on displaying server-generated images (specifically matplotlib graphs) in a ReactJS module without needing to save the files on the server. To achieve this, I decided to use base64 to create an image string. When it comes time to sh ...

Incorporate PHP form and display multiple results simultaneously on a webpage with automatic refreshing

I am currently in the process of designing a call management system for a radio station. The layout I have in mind involves having a form displayed in a div on the left side, and the results shown in another div on the right side. There are 6 phone lines a ...

Best practices for incorporating and leveraging node packages with Laravel Mix

As I embark on my Laravel (v 8.x) Mix project, I am encountering challenges when it comes to incorporating JavaScript from node modules. To kick things off, here is a snippet from my webpack.mix.js: mix.js('node_modules/mxgraph/javascript/mxClient.mi ...

Is it possible to utilize `const` in place of `let` universally?

When utilizing flowtype, our preference is to use const over let I have a function that needs to be executed with optimal performance, and it effectively compares two arrays with ids. This serves as a great example for my question: /** * @function compar ...

Concurrent execution within a Node.js function

I am facing a challenge with my function that deals with 1400+ crypto pairs. Each pair requires an API call and data storage, resulting in a significant amount of time for the entire process. The bottleneck occurs because each pair takes approximately 3-4 ...

Searching for a four-digit number within a string using NodeJS Regex, alongside specific keywords

I have a regex pattern that should match strings with a specific year format. The template is 'Year--"high OR low"-level'. Here is the regex I've created: /Year-\d{4}-\b(low|high)\b-level/gi; When I test it using online regex ...

Sending the "Enter Key" using JavaScript in Selenium can be achieved by utilizing the "executeScript" function

I'm currently developing an automation flow using IE 11 with Selenium and Java. On a particular web page, I need to input a value in a Text Box and then press Enter. I have successfully managed to input the values using the following code: // The &ap ...

Using the && operator in an if statement along with checking the length property

Why does the console show 'Cannot read property 'length' of undefined' error message when I merge two if conditions together? //When combining two if statements using &&: for(n= 0, len=i.length; n<len; n++) { if(typeof ...