The Raycaster object in Three.js is not defined when trying to trigger a

I'm currently using a raycaster with mousemove to change the cursor and it's working really well! However, I've noticed a little issue - it seems to only work properly when the mouse is over either the model or the box itself. If I hover into a blank space where there's nothing, it kind of breaks and I get an undefined error... For example, if I hover over the box and the cursor changes to a pointer, then move off the box but end up hovering over the model behind it, the cursor changes to auto as expected. But if I then hover into a blank space where there is nothing, the cursor stays as a pointer instead of changing to auto.

function onDocumentMouseMove(event) {

    event.preventDefault();
    var mouse = new THREE.Vector2();
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

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


    if (intersects[0].object.name == 'MaBox') {
        container.style.cursor = 'pointer';
        console.log('Mouse is over')
    } else {

        container.style.cursor = 'auto';
        console.log('Mouse is off')
    }
}

Error:

Uncaught TypeError: Cannot read property ‘object’ of undefined at HTMLDocument.onDocumentMouseMove

Does anyone have any suggestions on how to fix this?

Answer №1

Make sure to verify that the array of intersects actually contains elements. If it's empty, there won't be any element at index 0.

Here is an example:

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

    if (intersects.length > 0) { // check if the array is not empty

        if (intersects[0].object.name == 'MaBox') {
            container.style.cursor = 'pointer';
            console.log('Mouse is over')
        } else {
            container.style.cursor = 'auto';
            console.log('Mouse is off')
        }
    }

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

Retrieve the image description using the file_picker_callback and image uploader in Tinymce

TL:DR I am attempting to retrieve the value of the image_description field using JavaScript to include it in my post XHR request Original query: I am utilizing the file_picker_callback type image I have enabled the image_description input field in my ...

Unable to locate Node.js /socket.io/socket.io.js on express 4.0

Currently, I am working on implementing a chat feature on my website. During testing on my local server, everything was running smoothly as port 8080 on localhost was readily available. However, after deploying my code to Heroku, I encountered an issue whe ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Convert a form into plain text utilizing CSS with minimal usage of jQuery or Javascript

I am working on an HTML page which has a form with various tags such as checkboxes, dropdowns, and more. When a button is clicked, I want to display the same form as plain text in a popup using jQuery dialog. Currently, I have managed to show the form in ...

In express.js, cookies automatically expire upon the browser being closed

When working with express.js, I typically set cookies using the command: res.cookie("name", "value"); However, upon closing and reopening the browser, I noticed that the cookie is no longer there. Could someone advise me on how to mak ...

Activate Keyboard and Background in the Bootstrap Modal

I have set up my modal to disable the escape key and backdrop by default. $(modal).modal({ backdrop: "static", keyboard: false }); However, at a later time, I want to enable them again. $(modal).modal({ backdrop: true, keyboard: true }); The is ...

Creating a Redirect Form that Directs Users to a Specific Page Depending on Input Data

Apologies if this is a basic issue, but I'm struggling to figure it out. I am trying to create a form field on a webpage that will redirect users to a specific page based on the data they input. For example, if someone types in "dave" and submits the ...

Value becomes null when updating in Node.js

I've been working on updating a value through API calls in express and node js. Here is how my route is set up: var express = require('express'); var router = express.Router(); router.put('/updateValue/:id', function(req, res, ne ...

Steps for inserting a JSON Array into a database

I have a dropdown menu that displays different options based on the selection from another dropdown. The data for each dropdown is fetched from the database and I need to insert the selected values into a new table in the database. All the necessary code ...

What is the best way to implement a JavaScript pattern matching for both "aaaa" and "aaa aaa"?

Can anyone help me create a pattern that can accept both strings with spaces and without spaces in the same text box? I would appreciate any guidance on how to achieve this. Thanks! ...

The selected jquery script is failing to function as intended

I'm currently implementing jQuery chosen in a select element to enhance user experience, however I'm facing an issue when attempting to copy the chosen div to another div using jQuery $(document).ready(function() { $(".chosen").chosen({}); ...

Is there a way to properly direct to an internal page while utilizing [routerLink] and setting target="_blank" without triggering a full page reload?

I'm attempting to use [routerLink] along with target="_blank" to direct to an internal page without triggering a full app reload. Currently, the page opens in a new tab, but the whole application is refreshed. Here is the HTML: <a [routerLink]=" ...

Redis method LRANGE is returning a list in a way that doesn't meet my requirements

I have a significant amount of data stored in redis which I am caching. When I need to retrieve this data, I use the lrange function to fetch it. The issue is that when the data is returned, it is in a format like this: https://i.sstatic.net/r1oa8.png Ho ...

npm encountered an issue: EPERM error - the operation is not permitted and cannot unlink the file

Operating System: Windows 10. NPM Version: 6.9.0 Node Version: 12.4.0 I am currently developing an Expo application. I am attempting to install all the necessary packages for my Expo application using 'npm install'. However, I encountered an err ...

implement a new directive in AngularJS that references another directive in HTML

Check out the Fiddle here Upon button click, a modal window appears. Inside this modal, there is a <template-placeholder></template-placeholder>. When the button is clicked, an if-check is performed to ensure it's the correct button. If ...

Is it possible to combine the existing request parameters with a new parameter in JSP/JSTL/JQuery?

Here is a sample URL: http://127.0.0.1:8080/admin/seller?email=tim%40example.com Below is a snippet of JSP code: <a class="btn btn-primary ${page==pages||pages==0?'disabled':''}" href="?page=${page + 1}">Next</a> I am ...

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

Issue with Material-UI NativeSelect not correctly displaying preselected option

I have the following code snippet: <NativeSelect classes={{ icon: classes.icon }} className={classes.select} onChange={this.onVersionChange} > { Object.keys(interface_versions).map(key => { return <optio ...

Showcasing a dynamically created JSON document on a basic web page

Looking for a solution to display the contents of a result.json file generated by my Java tool on a simple website. I am aware that accessing local files directly with JavaScript is not possible, so seeking alternative methods that do not involve using a w ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...