How do I deactivate dragControls in THREE.JS after enabling them for a group of elements?

My function currently activates dragControls when the "m" key is pressed, but for some reason, it doesn't deactivate when the key is released. How can I go about disabling the dragControls?

I attempted to encapsulate the dragControls activation based on a true/false statement, setting dragControls to null when the statement is false. However, even after the initial activation, the dragControls remain active when the statement is false. Using while and do while loops only ends up freezing the browser.

  init() {
  // EVENT LISTENERS:
  map.addEventListener('mousedown', this.movePoi, false);
  document.addEventListener('keydown', this.onDocumentKeyDown, false);
  document.addEventListener('keyup', this.onDocumentKeyUp, false);

},

// HELPER FUNCTIONS:
onDocumentKeyDown(event) {

  let keycode = event.which;
  if (keycode === 77) {
    this.moveIt = true;
    this.controls.enabled = false;
    console.log("Key is pressed");
    console.log(this.moveIt);
  }
},
onDocumentKeyUp(event){
  let keycode = event.which;
  console.log(keycode);
  if (keycode === 77) {
    this.moveIt = false;
    this.controls.enabled = true;
    console.log("Key is unpressed");
    console.log(this.moveIt);
  }
},
mouseOverScene (event) {
  event.preventDefault();
  let rect = event.target.getBoundingClientRect();
  let x = event.clientX - rect.left;
  let y = event.clientY - rect.top;

  this.mouse.x = ( x / this.mapWidth) * 2 - 1;
  this.mouse.y = - ( y / this.mapHeight ) * 2 + 1;

  this.rayCaster.setFromCamera(this.mouse, this.camera);
},

//POI movement around the scene:

movePoi (event) {

  event.preventDefault();
  let controlsDrag;
  if (this.moveIt) {
  controlsDrag = new DragControls(this.spheres, this.camera, this.renderer.domElement);

  } else {
    controlsDrag = null;
  }
}

EXPECTED: I want the objects to be draggable with a left-click mouse while the "m" key is pressed (where the orbitControls are disabled), and when the "m" key is released, they should return to a non-draggable state with the orbitControls enabled again.

ACTUAL: The objects are indeed draggable when the "m" key is pressed (with the orbitControls disabled), but even after releasing the key, the objects remain draggable. This leads to chaos on the screen with the orbitControls enabled.

Answer №1

While not yet proven through testing, one potential solution could be to invoke the movePoi function within the onDocumentKeyUp event. It appears that the current logic only checks for the "m" key press when the mouse left button is clicked, rather than when the "m" key is released. Implementing this adjustment may resolve the issue at hand.

Answer №2

So, here is how the solution unfolds:

  init() {
  
        this.controlsDrag  = new DragControls(this.spheres, this.camera, this.renderer.domElement);
      this.controlsDrag.deactivate();
      
  // EVENT HANDLERS:
  
      map.addEventListener('mousedown', this.startMovePoi, false);
      this.controlsDrag.addEventListener('mouseup', this.stopMovePoi,false);
},

//Moving Points of Interest (POI) around the scene:
    startMovePoi () {
      let controls = this.controls;
      this.controlsDrag.activate();
      this.controlsDrag.addEventListener('dragstart', function () {
        controls.enabled = false;
      });
      this.controlsDrag.addEventListener('dragend', function () {
        controls.enabled = true;
      });
    },
    
    
    stopMovePoi(){
      this.controlsDrag.deactivate();
    }

Some code restructuring was required earlier.

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 using Google Maps Autocomplete, always make sure to input the full state name instead of just the state

Utilizing the Google Maps autocomplete API, we have enabled our customers to search for locations in the format of city, state, country. The functionality is effective overall, but a recurring issue arises when searching for cities, such as 'Toronto&a ...

What is the best way to transform the pages extracted through the Notion API into slugs?

I'm new to Next.js and Notion API, and I want to create a blog site on my personal website using the Notion API. While I can easily pull the posts, I am facing a challenge in slugifying the endpoint IDs with post titles. When attempting this based on ...

Prevent the default scroll event triggered by the mousewheel in certain situations. It is not possible to use preventDefault within a passive event

I have a div element with the onWheel attribute. By default, the browser interprets onWheel as scroll behavior. However, I want to prevent the browser's default mouse behavior under certain conditions. Unfortunately, I encountered an error that say ...

What is the indicator that signals a change in the value of a React ref.current?

Typically, when using props, we would write componentDidUpdate(oldProps) { if (oldProps.foo !== this.props.foo) { console.log('foo prop changed') } } to identify any changes in props. However, if we utilize React.createRef(), how can w ...

Troubleshooting: Issues with jQuery's Class selector

Having trouble setting up an alert to trigger when a specific class anchor tag is clicked inside a div. This is what my HTML section looks like... <div id="foo"> <a class='bar' href='#'>Next</a> </div> And h ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

State update failing to modify arrays

Shown below is an array that contains boolean values: const [state, setState] = React.useState({ [`${"checkedA"+index}`]: false, [`${"checkedB"+index}`]: false, [`${"checkedC"+index}`]: false, [`${"checkedD"+index}`]: false, }); ...

Utilize express.router() to send a get request to a third-party API while including an API key

As I develop my react application, I am faced with the task of retrieving data from a third-party site that requires me to include an API key in the header as 'X-Auth-Token'. Currently, I am using the fetch() API from the client-side JavaScript ...

What is the best way to clear the content of a contenteditable element in React?

I have a scenario where I am rendering an array of items, each with a contenteditable field. MainComponent.js import { useState } from "react"; import Item from "./Item"; import "./styles.css"; export default function MainC ...

What are some strategies for handling analytics tracking in Flux architecture?

Imagine I'm working on a cutting-edge single page application similar to Airbnb. One essential aspect of such an application is keeping track of when someone signs up for an account. There are numerous services available to assist with tracking, incl ...

Using back end proxy for content delivery

I am facing a challenge with my iOS app that requires proxying through a private server (HTTP / HTTPS proxy). Every time I attempt to address this issue on the client-side, new problems arise. How can I use the back end to effectively solve this problem? ...

Automating the process of submitting a checkbox

Displayed below is a mix of HTML and JavaScript: <form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>"> <input type="hidden" name="user" value="<?php echo $employee->id; ?&g ...

Issue with React Native TextInput failing to update state within a functional component when onChange event is triggered

When using a TextInput in a React Native functional component, I am facing an issue where the state for "name" is not updating properly when onChange occurs. To debug this issue, I have added a console log in useEffect to monitor the new state value. Howe ...

Activating the spinning wheel page-loading indicator in the browser through Socket.IO

Currently, I am constructing a web application using Node.js along with Socket.IO for managing data transfer between the client and server components. The central component of my web app is a content feed. To fetch the contents of the newsfeed, my client- ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

Connect to Node-Red websocket server

My server is running node-red with embedded functionality. I am attempting to set up a new websocket listener on the server, but when I run the code provided, the websockets in my node-red application stop functioning properly. const WebSocket = require(& ...

Line numbers in Vue Codemirror

Currently, I'm working on integrating codemirror into my Vue.js application using a library found at https://github.com/surmon-china/vue-codemirror. The issue I'm facing is that even after importing and utilizing the codemirro component, everythi ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

Database only accepts numerical data for insertion, rejecting any characters or alphanumeric entries

On a webpage, I have an input field through which I am passing the value into an ajax POST request. After logging everything in my JavaScript file and confirming that all is working as expected. In my PHP file, I retrieve the input value using $message = ...