The raycaster's intersectObjects function is failing to work as expected in the three.js library, as it consistently returns

It appears that there is an issue with the function "raycaster.intersectObjects" in the context of Three.js r54. The relevant code snippet is as follows:

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 75;
scene = new THREE.Scene();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );

var raycaster = new THREE.Raycaster();
var mouseVector = new THREE.Vector2();

function onDocumentMouseDown( e ) {
    e.preventDefault();
    mouseVector.x = ( e.clientX / window.innerWidth ) * 2 - 1;
    mouseVector.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
    var intersects = raycaster.intersectObjects(scene.children, true);
    console.log(intersects);
    if (intersects.length>0){
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}

function render() {  
    requestAnimationFrame(render);           
    mesh.rotation.y += 0.005;
    renderer.render(scene, camera);
}

To troubleshoot the issue, I included a "console.log" statement in the code and observed that it consistently outputs an empty array in the console. This occurs regardless of whether I click on a specific object or just the background.

Answer №1

According to the documentation found at , it appears that you may have overlooked a crucial line:

// make sure to update the picking ray with the camera and mouse position    
raycaster.setFromCamera( mouseVector, camera ); 

It is essential to place this code right before calling raycaster.intersectObjects().

This applies specifically to three.js version r71.

UPDATE:

In three.js version r54, your onDocumentMouseDown() function should be structured as follows:

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

    var mouseVector = new THREE.Vector3(
        ( e.clientX / window.innerWidth ) * 2 - 1,
      - ( e.clientY / window.innerHeight ) * 2 + 1,
        1 );

    projector.unprojectVector( mouseVector, camera );
    var raycaster = new THREE.Raycaster( camera.position, mouseVector.subSelf( camera.position ).normalize() );

    // create an array containing all objects in the scene with which the ray intersects
    var intersects = raycaster.intersectObjects( scene.children );
    console.log(intersects);
    if (intersects.length>0){
        console.log("Intersected object:", intersects.length);
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}

Additionally, within the init() function, include the following line:

// initializing the object for world/screen calculations
projector = new THREE.Projector();

For a demonstration, refer to this jsFiddle link: http://jsfiddle.net/5z13yzgx/

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

Is there a way to invoke a function using $scope within HTML that has been inserted by a directive in AngularJS?

After moving the following HTML from a controller to a directive, I encountered an issue where the save button no longer functions as expected. I attempted to change the ng-click to a different function within the directive code, and while that worked, I u ...

Share the Nav tag value or name during an OnClick event within ReactJS

I've been facing a minor issue that I just can't seem to figure out - how do I pass a value to my OnClick event? It's crucial for me to pass this value as it corresponds to the options in my menu and is essential for some processes: This is ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Certain images are being rotated in a counter clockwise direction by 90 degrees

Users can upload images of their items, but some pictures appear rotated 90 degrees counter-clockwise after uploading. This could be due to the way the photos were taken on an iPhone. Is there a simple solution to correct this rotation issue? The following ...

Dynamically injecting a JavaScript script within a Vue.js application

Is there a way to dynamically load a JavaScript script within a Vue.js application? One approach is as follows: <script async v-bind:src="srcUrl"></script> <!--<script async src="https://cse.google.com/cse.js?cx=007968012720720263530:10 ...

Refreshing ng-repeat dynamically with $http without reloading the page

Just a quick heads-up, I'm new to AngularJS In my AngularJS application, I am using the $http service to fetch data. Each row has an update button that needs to trigger a server-side method (the API is already returning data) to sync with a third-par ...

Implementing React with multiple event listeners for a single click event

One of the challenges I'm facing is with a function called playerJoin() in my React app. This function is triggered when a specific button is clicked. It sends data to the server, which then checks if the information matches what is stored. If there i ...

Issue with Github actions: Failure in mark-compacts process due to ineffective operation near heap limit causing allocation failure - running out of memory in

Whenever I try to build my library files, I keep encountering an out of memory error. In my local setup, I was able to resolve this problem by executing the command export NODE_OPTIONS="--max-old-space-size=8192". Unfortunately, no matter how mu ...

Use PHP to redirect a webpage as an alternative to utilizing JavaScript

Recently, I encountered an issue where I created a form on inde1.php and utilized JavaScript to post data to login.php. My current goal is to redirect the user to another page once login.php has been successfully executed. Below is the JavaScript code on ...

Is it possible to serialize the entirety of a website's Javascript state, including Closure/Hidden scopes?

My goal is to capture a "snapshot" of a webpage while maintaining its interactive functionality, allowing all Javascript states to be saved and restored. An example scenario where this would be beneficial is when a webpage contains script that utilizes glo ...

Tracking user's interactions with hyperlinks on my website

I operate a website where I enable other developers to host content. My goal is to track clicks on every hyperlink, including those that lead to content hosted by other developers. Initially, I approached this problem as follows: $('a').click(f ...

What is the best way to access nested objects in React Native?

Here is the JSON data I am working with: [ { id: 51, name: 'Boat Neck Blouse', image: { id: 669, date_created: '2018-08-27T10:05:39', date_created_gmt: '2018-08-27T10:05:39', date_modified ...

How to modify a single entry in a MongoDB database with the help of Node.js and

How do I update a specific record by _id in a MongoDB collection? A recent UPDATE: After making some changes to the code, I now encounter a 500 internal server error. Any suggestions on resolving this issue would be greatly appreciated. "_id ...

Export your Blender 2.7X models to .json format for easy integration with three.js JSONLoader

Currently, I am facing a challenge with exporting from Blender to Three.js using the JSON format specifically for animations. The version of Three.js that I am working with is r71 As for Blender, I am using version 2.74 It seems that the current Blender ...

When using a JavaScript associative array, there are often many fields that are

I'm working with an associative array where the key is the item's ID. For example, if the item has an ID of 104, then the object would be array[104] = {item.info}; However, when I output my array in the component, it displays values from 1-103, ...

What is the best way to cut and combine multiple array elements in the right positions?

let result = response.data; console.log(result); const newTemp = result.ssps_with_scated.splice(5,1).concat(result.ps_with_ed.splice(2,1))[0]; result.ps_with_ed.push(newTemp); After multiple attempts, I finally achieved my goal. However, the array values ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...

Generate Bootstrap 5 Navbar <li> and <ul dropdown item> dynamically using JavaScript

Requesting assistance I have stored text in the constant.js file as shown below. export const navLinks = [ { id: "manage", title: "Manage", }, { id: "transactions", title: "Tran ...

Troubleshooting a problem with the `.toggle()` function in

My form includes a question where multiple answers, including "Others," can be selected by ticking checkboxes. When the "Others" option is ticked, a textbox should appear, and when unticked, the textbox should hide. The issue I'm facing is that even ...

Is it necessary for children to occupy the same area while beginning from the coordinates 0, 0?

Imagine a scenario where you have a modal with tabs and tab content. Each tab has a different height - the first tab is 100px high, the second tab is 500px high, and the third tab is 50px high. The challenge here is to ensure that the modal body always mat ...