Avoiding accidental clicks on a raycasted object while moving the mouse

I am dealing with a group of clickable objects that can be rotated by using the scroll wheel or by clicking and dragging. The issue I am facing is that when you release the click on top of an object after dragging, it triggers the click animation.

Here is a link to a simplified version of the project on fiddle.

Does anyone have a solution to prevent the click action from being recorded during the drag operation? It seems to be more complex because the objects are raycasted.

Below are my JavaScript functions:

document.addEventListener("mousedown", function () {
    isMouseDown = true
    startX = event.pageX
    startY = event.pageY
    document.body.style.cursor = 'grabbing';
  })

  document.addEventListener("mouseup", function () {
    isMouseDown = false
    document.body.style.cursor = 'grab';
  })

  document.addEventListener("mousemove", function (event) {
    if (isMouseDown) {
      document.body.style.cursor = 'grabbing'
    }

    aimX = ((window.innerWidth / 2) - event.pageX) * 0.35
    aimY = ((window.innerHeight / 2) - event.pageY) * 0.5

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

    raycaster.setFromCamera(mouse, camera)

    const intersections = raycaster.intersectObjects(group.children)

    if (intersections.length > 0) {
      if(projectHov){
        if (INTERSECTED != intersections[0].object) {
            if (INTERSECTED)
            INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
            INTERSECTED = intersections[0].object;
            INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
            //setting up new material on hover
            INTERSECTED.material.color.setHex( 0xadadad );
            if (INTERSECTED){
              if(projectHov){
                document.body.style.cursor = "pointer"
              }
            }
        }
      }

      } else {
          if (INTERSECTED) INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
          document.body.style.cursor = "grab";
          INTERSECTED = null;
      }

// Moving the objects ==========================
    if(isMouseDown) {
      let currentRotation = new THREE.Matrix4();
              currentRotation.makeRotationFromEuler(group.rotation);

              let newEuler = new THREE.Euler(0, ((event.pageX - startX) + (event.pageY - startY)) / 325, 0);
              let newRotation = new THREE.Matrix4();
              newRotation.makeRotationFromEuler(newEuler);

              let finalRotation = new THREE.Matrix4();
              finalRotation.multiplyMatrices(newRotation, currentRotation);

              group.rotation.setFromRotationMatrix(finalRotation);

              startX = event.pageX;
              startY = event.pageY;
    }
  })
section.addEventListener('click', onDocumentMouseDown, false);

  function onDocumentMouseDown(event) {
      event.preventDefault();
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
      raycaster.setFromCamera(mouse, camera);
      const intersections = raycaster.intersectObjects(objects)

// Animation =================================
          if (intersections.length > 0){
            if(projectHov){
              tl.play();

              tl.to(backTag, 1, {
                delay: 1.25,
                autoAlpha:1,
              }, 0);

            }

// Animation ===================================
            if (intersections[0].object == old ) {
              if(projectHov){
                tlOld.play();
                projectHov = false
                tlOld.to(old, 1.5, {three:{scaleX: 1.5, scaleY: 1.5, x:0, y:0, z:0}, ease:Power2.easeInOut}, 0);
                tlOld.to(fnup, 1, {three:{y:-4000, opacity: 0 }, ease:Power2.easeInOut}, 0);
                tlOld.to(alex, 1, {three:{y:-4000, opacity: 0 }, ease:Power2.easeInOut}, 0);
                tlOld.to(cam, 1, {three:{y:-4000, opacity: 0 }, ease:Power2.easeInOut}, 0);
                tlOld.to(mirrorCube, 1, {three:{y:-400, opacity: 0 }, ease:Power2.easeInOut}, 0);
              groupRotate = false
            }

            } 

Answer №1

Consider saving the UUID of intersections[0].object in a variable and keeping it updated during mouse events. Compare this stored UUID with the UUID of the object hit by the raycast on mouse up. Only proceed with further processing if the two UUIDs match.

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

Creating JSON from identical user interface components

I have created a form similar to this one: https://jsfiddle.net/6vocc2yn/ that generates a JSON output like below: { "List": [ { "Id": 10, "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10", "email": "<a href="/cdn-cgi/l/email-pr ...

Is there a way to connect two tables using CSS pseudo-selectors?

Is there a way to make two separate tables interact with each other using CSS pseudo-selectors? I have a data table and an auto-numbered table, and I want the rows to highlight in both tables when hovering over a cell in one of them. I've tried using ...

Is there a way to generate and transmit a text file using XmlHttpRequest or $.ajax?

The server is anticipating an html or txt file to be sent from a form named "websitetopdf". The file is dynamically created on client javascript and should only function properly on Chrome. Below is the form that needs to be used for sending: <form ac ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

Displaying Hierarchical Data with AngularJS and ng-repeat

Recently, I've been working on finding an elegant solution to represent hierarchical data in my application. Specifically, I have implemented a slide effect for bootstrap badges that showcase sub-categories using AngularJS. With some guidance from th ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

Three.js: Spherical boundary of an object that has been resized

When working with a collection of 3D shapes such as pyramids, cubes, octahedrons, and prisms, I encountered an issue with building described spheres around them. While it's straightforward to create the spheres using geometry.boundingSphere due to its ...

unusual behavior when using the CSS property transform: rotate

i'm attempting to enable this element to be both draggable and rotatable. However, when I apply transform:rotate(0deg);, I am able to drag it anywhere within the parent container. But when I set it to 90deg, there are certain areas that become undrag ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...

What is the process for enabling the experimental-modules option when running an npm package's bin command?

Beginning with Node v8.5.0, the support for ES6 style modules has been introduced. import x from 'x' You can access this feature by running node using the --experimental-modules option, like so: node --experimental-modules test.mjs By utilizi ...

Preventing Paste Function in Electron Windows

Currently, I am utilizing Electron and attempting to prevent users from pasting into editable content. While paste and match style remains enabled, the functionality is flawless on Mac devices. However, there seems to be an issue on Windows where regular ...

Unable to assign headers once they have already been sent to the recipient - a Node.js error

Encountering an error message stating "Cannot set headers after they are sent to the client." I've researched and it seems like multiple callbacks may be causing this issue. However, I'm struggling to find a solution. Any assistance in resolving ...

I am confused about the process of mounting components

Utilizing pattern container/representational components, I have a CardContainer component that retrieves data from a server and passes it to a Card component. Container Component: class CardContainer extends Component { state = { 'ca ...

Why is My TensorFlow.js Model for Predicting 2 Table Multiples Not Producing Accurate Results?

I have created a tensorflow.js model that predicts outputs in multiples of two. For example, if the input is 16, the prediction should be 32. However, even after providing the input data and labels accordingly, the output printed is [[1],] after prediction ...

Executing Client-Side Function Upon Data Retrieval in a Node.js Application

Within my node.js Express application, there exists a route like this: router.get('/devices/:id/visualize', catchErrors(deviceController.visualizeDevice)); This route points to the following controller: exports.visualizeDevice = async (req, re ...

What is the method for positioning the cursor at the beginning of a center-aligned placeholder within a contenteditable element?

Here is the code snippet I am working with: HTML: <div class="title" contenteditable="true" placeholder="Title"></div> CSS: .title { width: 500px; margin: 0 auto; text-align: center; } [contenteditable=true]:empty:before{ conte ...

Unable to transmit a collection of JavaScript objects in a node.js environment

Below is the code snippet I am currently working with: app.get('/posts',function(req,res){ console.log(posts); res.send(posts); res.send(200); }); I am using the following approach to retrieve and display an array of JavaScript objects (posts ...

Sorry, but we couldn't complete your request: User verification unsuccessful: email must be provided

Every time I attempt to save a user's credentials to the mongo database, an error pops up saying: "User validation failed: email: Path email is required." I am clueless as to why this issue keeps happening. It only started occurring when I added the v ...

Encountering a Javascript 404 error while attempting to make an API call

I encountered an issue while trying to modify data in my database. When my api request is made, I am receiving the following error: Uncaught (in promise) SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Additionally, I am r ...

Expecting function to return an undefined response object

My experience with async/await is limited, but I have used these keywords in a function that retrieves or posts data to a MongoDB database. However, it seems like the await keyword does not wait for the promise to be fulfilled and instead returns an undefi ...