Javascript Mouse Events Not Functioning Properly with Three.JS Scene Components

Currently feeling quite perplexed (probably due to fatigue from working on this at an inopportune time). I'm in the midst of trying to configure my three.js application to trigger distinct functions based on different mouse events when the cursor hovers over a specific entity in my scene. Surprisingly, events of the "mousemove" variety are functioning flawlessly, as evidenced by the

console.log( 'INTERSECTED.isGraphElement: ', INTERSECTED.isGraphElement, 'MouseEvent: ', mouse.type );

which successfully captures all the mouse events I've designated to monitor, encompassing "mousemove", "click", "dblclick", "wheel," and "oncontextmenu". Notably, it also correctly identifies INTERSECTED.isGraphElement objects.

However, despite this progress, only the "mousemove" events appear to be triggering within the transformGraphElement function when transformGraphElement() is called. Even when the commented-out code line meant to display "Got the dblclick!" is omitted. It seems that none of the other mouse events I'm monitoring are being recognized here.

Several approaches I've attempted within the transformGraphElement function include:

  • Replacing the dblclick event with another of the monitored types. No luck.
  • Disabling the line for handling mousemove events. No luck.
  • Verifying for bugs within my
    obj.referent.transformOnDblClick()
    function. This unveiled that the function wasn't being invoked at all (although it functions perfectly when linked to the "mousemove" event).
  • Experimenting with different valid syntaxes for my 'if' statements. No luck.
  • Conducting some restructuring within the mouseEventHandler() function. No luck.

Below is the pertinent code excerpt:


// Code snippet here
The text you provided has been modified to be unique. Let me know if you need any more assistance.

Answer №1

Upon waking up the following morning, I immediately identified the root of the problem, which stemmed from a flaw in the code's logic:

if (mouse.type === 'mousemove'), with further conditionals for different event types. Here is the revised code, with some refactoring to enhance readability:

var ray = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var INTERSECTED;  // Object closest to the camera

function onMouse( event ) {

    event.preventDefault();

    // Calculate mouse position in normalized device coordinates (-1 to +1) for both components
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    mouseEventHandler( event /*, transformGraphElement, unTransformGraphElement */ );

}

function listenFor(){
    document.addEventListener( 'click', onMouse, false );
    document.addEventListener( 'mousemove', onMouse, false );
    document.addEventListener( 'mousedown', onMouse, false );
    document.addEventListener( 'dblclick', onMouse, false )
    document.addEventListener( 'wheel', onMouse, false );
    document.addEventListener( 'contextmenu', onMouse, false );
}

listenFor();

/* ... */

function render() {

    requestAnimationFrame( render );
    renderer.render(scene, entities.cameras.perspCamera );
}

function mouseEventHandler( event /* , fn, revFn */ ){

    // Update the picking ray with the camera and mouse position
    ray.setFromCamera( mouse, entities.cameras.perspCamera );

    // Calculate objects intersecting the picking ray
    var intersects = ray.intersectObjects( scene.children );

    // If there's at least one intersected object...
    if ( intersects && intersects[0] && intersects[0].object ){

        // Check for mouse move event and ensure INTERSECTED object exists and remains the same        
        if ( event.type === 'mousemove' ){
            if ( intersects[ 0 ].object != INTERSECTED ){
                if ( INTERSECTED ) {    
                    unTransformGraphElementOnMouseOut( INTERSECTED, event );                                    
                }                       
                INTERSECTED = intersects[ 0 ].object;       
                transformGraphElementOnMouseOver( INTERSECTED, event );                         
                }   
        }

        // Handle double click mouse event 
        if ( event.type === 'dblclick' ){
            if ( intersects[ 0 ].object === INTERSECTED ){
                transformGraphElementOnSelect( INTERSECTED, event );                            
            }
            if ( intersects[ 0 ].object !== INTERSECTED ){
                if ( INTERSECTED )
                    unTransformGraphElementOnUnselect( INTERSECTED, event );                                
            }
        }       

    INTERSECTED && console.log( 'INTERSECTED.isGraphElement: ', INTERSECTED.isGraphElement, 'MouseEvent: ', event.type );           
    }
}

function transformGraphElementOnMouseOver( obj, event ){
    if ( obj.isGraphElement ) { obj.referent.transformOnMouseOver(); }  
}

function unTransformGraphElementOnMouseOut( obj, event ){
    if ( obj.isGraphElement ) { obj.referent.transformOnMouseOut(); }
}

function transformGraphElementOnSelect( obj, event ){
    if ( obj.isGraphElement ) { obj.referent.transformOnDblClick(); }   
}

function unTransformGraphElementOnUnselect( obj, event ){
    if ( obj.isGraphElement ) { obj.referent.unTransformOnDblClick(); } 
}

While certain issues in the logic of mouseEventHandler() remain, the fundamental problem has been addressed. Additionally, some refactoring has been carried out for improved clarity:

  • Eliminated the need to include event.type in mouse.
  • Moved the call to mouseEventHandler() from render() to onMouse(), ensuring events are registered only once.
  • Removed the 'fn'/'revFn' callbacks in mouseEventHandler() for simplification.
  • Removed event as a parameter for the transform functions.

I hope this revised version proves helpful to others.

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

When I log them out, Node.js express always manages to bail me out even when Object is not defined

While attempting to destructure an object in my express middleware: const verifyLoggedInStatus = (req, res, next) => { try { const token = req.cookies['jwt-auth'].token; console.log('token: ', token); req. ...

What steps can be taken to ensure web resources such as scripts, images, etc are loaded from the correct location when implementing CORS support in a web application

In my local IIS, I have two asp.net mvc applications running on different ports. One is "App1" on port 1066 and the other is "App2" on port 1067. My requirement is for App2 to post data to an endpoint in App1 for validation. If the data is valid, App1 sho ...

How come WhatsApp is not recognizing my og:tags correctly?

I'm having an issue with my webpage where the og:tags generated for link previews on Facebook work fine, but they can't seem to be scraped by WhatsApp. Even though the tags are correct in the source code of the site, WhatsApp shows an error messa ...

Guide: How to transfer the output from MongoDB in Node.js to AngularJS?

Currently, I am using Node.js to query my data from a MongoDB database. However, I am facing an issue where the data is not being sent out as expected when running this particular function. var findIco = function(db, callback) { var cursor = db.collec ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

express-session is failing to maintain persistence and refusing to transmit a cookie to the browser

I am currently developing a web application using the MERN stack (React, Node.js, Express, and MongoDB). I have integrated express-session in my Node.js project, but for some reason, I cannot see the connect.sid cookie in the browser. Additionally, it appe ...

What is the best way to switch from rows to cards in Bootstrap version 5.3?

In my current project, Next JS is the framework I am working with. I am faced with the challenge of creating a card layout that adapts based on device size - for smaller devices, I want a plain card with the image on top and text below, similar to Bootstra ...

Is there a way to modify the appearance of blocks in Scratch/Blockly?

I am currently working on customizing the appearance of the blocks in Scratch by looking into adjusting the GitHub repository of scratch-blocks (https://github.com/LLK/scratch-blocks). There is a chance that I might need to modify the GitHub repository of ...

Tips for accessing an element using a specific identifier with the variable $key

PHP //This is the HTML code for quantity <p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/> JS function function findTotal() { var arr = document.getElementsByName('qty'); // Calc ...

Guide on importing a React.Component from a Content Delivery Network (CDN) and displaying it within a separate React

Note: None of the solutions provided are effective [DO NOT REMOVE THIS NOTE] Here's a simple question for you - I have a project named Project Y, created using the command npx create-react-app react-project. Now, in the App.js file of Project Y, I h ...

Set a maximum frame rate for your aframe project

I'm currently working on an aframe project on my late 2013 MacBook Pro. No matter which browser I use (Firefox, Safari, Chrome), the fan on my computer spins rapidly when running the project, even with a simple a-box. The aframe-stats indicate that my ...

"Uh oh! Encountered an error while trying to extend an unrecognized button type: copyHtml5. Here's a guide on utilizing datatables.net-buttons-bs4

I recently installed Datatables using npm and added the necessary packages: npm install --save datatables.net-bs4 npm install --save datatables.net-buttons-bs4 Now, I also want to include the buttons.html5 js file in my project. Previously, I used CDNs ...

Can a React component be configured to show only a specific array key when returning an array?

Just diving into the world of react and experimenting with different approaches to understand how I can transition into this new architecture. Currently, I have a basic component where I am returning an array of elements (mainly for testing purposes): cl ...

Transmit data from the Windows Communication Foundation to JavaScript

Looking to invoke the WCF service through JavaScript, utilizing AJAX? Check out this resource: Calling WCF Services using jQuery Here's my query: Is there a method to retain some JavaScript-related data after making a request, and then transmit inf ...

Issues with JavaScript causing YouTube embed player to malfunction

For the past few days, I've encountered an issue where my JavaScript code to embed YouTube videos isn't working properly. The video loads but it's not playable as the play button is unresponsive. The console shows this error: Uncaught TypeE ...

Pass the ID of a dynamic textbox element to a child window upon clicking a link

One of the challenges I'm facing involves a textbox labeled "Branch Code" that links a branch to a corporate card transaction. At times, there is a requirement to split a transaction among multiple branches. To facilitate this process, I am constructi ...

Adding a hash to asset paths in NextJS static builds

After running next build && next export, I receive a directory named out, which is great. When examining the source code, such as in the index.html file, it requests assets from <link rel="preload" href="/_next/static/css/styles.aa216922.chunk. ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Time picker in Bootstrap - Ensuring end time is not earlier than start time validation

How to prevent users from selecting a past time for the end time in Bootstrap time picker with start time validation <html> <head> </head> <body> <link href="https://maxcdn.bootst ...

Voice crashes in Discord.js after the audio has been playing for a short while

Every time I try to play a song, the bot crashes and gives an "aborted" error message after about a minute. music = { "resource": createAudioResource(ytdl(parameters[0], {filter: "audioonly"}), {inputType: StreamType.Arbit ...