Ray casting problem with THREE.js - Intersections can be quite fickle, often failing to return any intersecting objects

My current issue involves using the Raycaster in THREE.js to focus on objects with the mouse position. While I've successfully done this many times before, something seems to be off in my current setup.

Strangely, the onFocus callback occasionally triggers, but most of the time it's the onBlur callback that is being called instead. Despite referencing examples and searching through Stack Overflow questions, I can't seem to pinpoint where I'm going wrong. The only notable difference I can find compared to previous instances is that usually, my camera is positioned at 0, 0, 0.0001, facing outwards towards the objects. However, this time around, the camera is placed above and looking down into the objects.

The camera coordinates are set at 130, 325, 194, while the object is located at 0, 0, 0.

Take a look at the code snippets below:

scene = new THREE.Scene();
scene.add(camera);

const geometry = new THREE.CubeGeometry(50, 50, 50);
const material = new THREE.MeshBasicMaterial( { color: 0xff00ff, wireframe: false } );
const mesh = new THREE.Mesh(geometry, material);
mesh.onFocus = () => {
    console.log('focus test');
}
mesh.onBlur = () => {
    console.log('blur test');
}
intersectableObjects.push(mesh);
scene.add(mesh);



const onMouseMove = ({ clientX, clientY }) => {
    const x = (clientX / window.innerWidth) * 2 - 1;
    const y = - (clientY / window.innerHeight) * 2 + 1;
    mouseVector.set(x, y);
    raycaster.setFromCamera(mouseVector, camera);
    castFocus();
}



const castFocus = () => {
    intersectableObjects.forEach((obj, i) => {
        const intersects = raycaster.intersectObject( obj, false );
        if (intersects.length) return obj.onFocus();
        obj.onBlur();
    });
}

Answer №1

It took me several hours of trial and error to uncover the problem with the Raycaster not functioning properly when using a small value for cameraNear.

Originally, I had set the camera near at 0.000001, but adjusting it to 0.01 resolved the issue completely.

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 onClose event is indeed triggered by the Material-UI Popover component

Utilizing the Material-ui Popover component, I have encountered an issue with its opening state. I created a function called handlePopoverClose to manage the closing action when clicking outside of the 'Hover with a Popover' element. The intentio ...

Unable to use onSubmit with enter key in render props (React)

I am looking to include a button within a form that can trigger the onSubmit event when the user presses the Enter key. Here is an example of a functional solution: <form onSubmit={() => console.log('ok')}> <button type="submi ...

"Enhancing Forms with Multiple Event Listeners for Seamless Sub

I'm working on creating a countdown timer with 3 buttons for controlling the timer: start, cancel, and pause. The timer itself is a text input field where you can enter a positive integer. I need to use core JavaScript, not jQuery Start Button: Init ...

Following the completion of every asynchronous operation, a callback will be executed

I am facing a situation where I have an array of images that are uploaded with a series of asynchronous operations as shown below: for ( let key in imageFileObject ) { const imageFile = imageFileObject[key] dispatch('get_signed_request', ima ...

Combining a variety of materials and textures enhances the capabilities of GLTF

As I delve into the issue at hand, it's important to note that I don't claim to be an expert in 3D modelling, texturing, and rendering techniques. While I do have a basic understanding, feel free to point out any errors in my approach. Apologies ...

Tips on creating a search query with date condition in the format of M/D/YYYY and stored as a string

In my collection, I have two fields structured like this: { "StartDate" : "1/2/2019", "EndDate" : "5/14/2019" } I need to write a find query to retrieve documents within the current date range. For example: db.collection.find({StartDate:{$lte: &a ...

Why does the details page consistently receive the final item from the list?

For my e-commerce project built with React, I have a section to showcase featured items. Currently, there are only 9 items marked as featured in my database. Additionally, I am working on a modal details popup page that appears when you click on any item. ...

Examining if elements in a mapped array have common values

Currently, I am working on creating a news feed with React and moment.js. By utilizing the .map method, I am able to display items with titles and content. My goal is to determine if an item was published in the same year and month as another item. In such ...

AngularJS, building a hash of resources

Is there a way, in an AngularJS controller, to take a URL and redirect that request to the best place for fetching JSON data? The VideoSearchCtrl is connected to the search form. Everything seems fine with the generated URL for the template, so I aim to us ...

Passing properties to delete items

When I click on the button, I want both the icon and the button to disappear. I've attempted a solution but it's not working correctly. Any help would be greatly appreciated. const Button = (props) => { const[toggleIcon, setToggleIcon]=React ...

React: How to retrieve values from a dynamic dropdown menu

For my React project, I have integrated ant design components. Currently, I am working on adding dynamic select functionality and retrieving the selected values. I have successfully implemented dynamic dropdown selection. However, I am facing an issue wi ...

Supabase authentication in a React app is causing a TypeError: Unable to access properties of undefined (specifically 'user')

In the development of my React application using Next.js, I've integrated Supabase for authentication. I've created a custom hook named useAuthentication to verify if the user is logged in and redirect them to the login page if they're not. ...

Utilizing React Render Props to Pass References Between Components

Is there a way to access a ref that is passed between two external components using render props? I am trying to achieve something similar to this example usage. function Component() { // how can I retrieve the `ref` here? return ( <A> ...

Is it possible to make each letter on a page a different color using JavaScript? I've noticed that there is always an additional set of span tags before each opening tag on the page

Page hosted using Google Drive Within the JS code: var doc_part = false; //denotes if a character is not part of the visible document var page_body; //function to generate random rgb values function randomInt(max, min) { return Math.floor((Math.ran ...

Creating a legitimate Angular 6 form模shape

I want to reset my form using the following method: public static resetDescriptionFields(i: any, component: any) { var formItems = component.form.get('items') as FormArray; var descriptionItem = formItems.controls[i].g ...

The DOM nesting validation has found an issue: It is not allowed for text nodes to be placed directly inside a <tbody> element

I'm puzzled by this warning message I keep receiving. It's preventing me from seeing the updated table. Warning: validateDOMNesting(...): Text nodes cannot appear as a child of <tbody>. Some have suggested that extra white spaces and diffe ...

Attempting to grasp the correct method for understanding For loops

Lately, I've been diving into teaching myself Node.JS and it has been quite an enjoyable experience. However, I've hit a frustrating roadblock that is really causing me some grief. For some reason, I just can't seem to grasp the concept of F ...

What is the best method to add an overlay div onto another div when hovered, with a grid-style layout?

I attempted to create a grid-like design where each div would display an overlay on hover. The overlay div includes two buttons that should be centered. Although I believe the logic of my code is correct, the position of the buttons and overlay is not ce ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...

gRaphael - the struggle of animating a line chart

Encountering an issue with the gRaphael javascript line chart library. Creating a line chart from a CSV file with five columns (# of minutes, time, waiting time, in treatment, closed, in location). Previously drew full chart without animation successfull ...