Implementing Conditional Drag and Drop Functionality with DragControl in three.js

Is there a way to toggle the activation status of DragControls based on the value of a flag called drag_flag? My current approach doesn't seem to be working as intended.

I would appreciate it if you could provide guidance on how I can achieve this correctly. Thank you in advance.

    var drag_flag = true;
    function change_drag_flag(){
      drag_flag = !drag_flag;
    }
    var objects = [];

    var scene = new THREE.Scene();

    let box_geometry = new THREE.BoxGeometry(1, 1, 1);
    var material = new THREE.MeshPhongMaterial();
    const box = new THREE.Mesh(box_geometry, material);
    objects.push(box);
    scene.add(box);

    var spotLight = new THREE.SpotLight(0xffffff);
    spotLight.position.set(5, 5, 5);
    scene.add(spotLight);
    spotLight = new THREE.SpotLight(0xffffff);
    spotLight.position.set(-5, 5, 5);
    scene.add(spotLight);

    var camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );
    camera.position.set(0.1, 4, 1);
    camera.lookAt(scene.position);

    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    var drag_controls = new THREE.DragControls(objects, camera, renderer.domElement);
    if(drag_flag===true){
      drag_controls.activate();
      drag_controls.enabled = true;
    }
    else{
      drag_controls.deactivate();
      drag_controls.enabled = false;
    }
    renderer.render(scene, camera);
<button type="button" onclick="change_drag_flag()">Change Drag Flag</button>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1e02180f0f2a5a445b5a5b5a445b">[email protected]</a>/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5f43594e4e6b1b051a1b1a051a">[email protected]</a>/examples/js/controls/DragControls.js"></script>

Answer №1

To witness the impact of enabling/disabling controls in your scene, you must ensure that the rendering occurs more than once. I've made some modifications to your code for a smoother functioning:

const objects = [];

const scene = new THREE.Scene();

// Creating a box
const box_geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhongMaterial();
const box = new THREE.Mesh(box_geometry, material);
objects.push(box);
scene.add(box);

// Adding spotlights
const spotLight1 = new THREE.SpotLight(0xffffff);
spotLight1.position.set(5, 5, 5);
scene.add(spotLight1);

const spotLight2 = new THREE.SpotLight(0xffffff);
spotLight2.position.set(-5, 5, 5);
scene.add(spotLight2);

// Setting up camera
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.set(0.1, 4, 1);
camera.lookAt(scene.position);

// Initializing WebGL Renderer
const renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// Implementing Drag Controls
const dragControls = new THREE.DragControls(objects, camera, renderer.domElement);

function toggleDrag() {
  dragControls.enabled = !dragControls.enabled;
}

function animate() {
  requestAnimationFrame(animate);

  // Activating/Deactivating drag controls based on their status
  if (dragControls.enabled === true) {
    dragControls.activate();
  } else {
    dragControls.deactivate();
  }

  // Rendering the scene with updated changes
  renderer.render(scene, camera);
}

animate();
body {
      margin: 0;
}
<button type="button" onclick="toggleDrag()" style="position:absolute">Change Drag Flag</button>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a6e72687f7f5a2a342b2a2b342b">[email protected]</a>/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20544852454560100e1110110e11">[email protected]</a>/examples/js/controls/DragControls.js"></script>

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

Resize the shape of an image's polygon

Is there a way to independently scale a specific polygon of an image on hover? For example, I have a world map and I would like to enlarge a country when hovering over it, then return it to its original size when no longer hovering. I am familiar with us ...

Using pre-set values for filters in a mongo selector: best practices

I am currently working on implementing filters for a mongo find query. The objective is to have the mongo selector limit the retrieved data based on the specified filters. However, if no filter is provided (the filter has a null or default value), then the ...

Angular momentum issue detected

Developing an android app with a search function that includes input type date. Attempted to parse the input date from 2017-5-10T17:00:00.000Z to 2017-5-10 using moment.angular. Although the search function works, it results in an error that prevents the a ...

Determining the position and offset of an element

Currently, I am facing a dilemma with my table of images. I want to add an icon to the corner of each image so that they align perfectly. I attempted to achieve this using relative CSS positioning, but it resulted in the icons extending beyond the cells an ...

Is there a way to show the text within a div tag in a tooltip without relying on jQuery?

Is there a way to display the text content of an HTML element inside a tooltip? I am struggling to achieve this, as I would like to have the word test appear in the tooltip, but it's not working. Unfortunately, we are not using jQuery in our code bas ...

What is the method for specifying a string argument type from a string list and executing a mongo db query?

Is there a way to specify the argument type in a function as a string from a list of strings in order to run a MongoDB query? Here is what I am currently attempting: users.services.ts async findOne(key: "_id" | "email" | "username", value: string) { ...

switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here. Is there a simpler way to achieve this? I currently have to create two clas ...

Issue with Animation not functioning properly when InterstitialAd is displayed

Ever since I was in grade 7, I have been passionate about building games and apps. Although I learned some XML back then, I lost my ambition over the years due to life's distractions. However, two weeks ago, I decided to teach myself Java and created ...

Rails - removing list item upon deletion of parent object

Currently working on a project app as part of a full stack developer bootcamp program. One of the features I'm implementing is a destroy method to remove an item from a list. Using AJAX requests, the goal is to dynamically remove the li element repres ...

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

The Debate: Single Javascript File vs. Lazy Loading

Imagine you're working on a massive javascript-powered web application with minimal page refreshes in mind, containing around 80-100MB of unminified javascript to give an idea of its scale. The theory is that by lazy-loading your javascript files, yo ...

Issue arises when trying to insert an image avatar onto a globe in three.js

I have successfully implemented a rotating 3D globe using three.js with the code provided below. HTML <canvas id="canvas"></canvas> JS let camera; let renderer; function main() { const canvas = document.querySelector('#ca ...

Tips on transferring data using indices to separate tables

To retrieve tables dynamically, the code logic will depend on the number of items selected in the left window visible in the image provided below. I am uncertain about the exact code that needs to be written within the onClick function of the button to shi ...

Encountering an issue with receiving "undefined" values while utilizing WordPress post metadata in AngularJS

Utilizing the Wordpress REST API v2 to fetch data from my functional Wordpress website to an AngularJS application. Everything is functioning properly, however when I attempt to access post meta such as "_ait-item_item-data", it returns an error stating "u ...

The iFrame is set to a standard width of 300 pixels, with no specific styling to dictate the size

My current challenge involves utilizing the iframe-resizer package to adjust the size of an iframe dynamically based on its content. However, even before attempting any dynamic resizing, I encounter a fundamental issue with the basic iframe: it stubbornly ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Navigating a JSON hierarchy in Node.js

I have a json file that needs to be parsed to identify its structure. Below is the code snippet I tried using: var fs = require('fs') var reqTemplate; var obj; fs.readFile('SampleData.js', 'utf8', function (err, data) { i ...

find the intersection point of two elements

Is it possible to identify the exact point where two elements overlap? Take a look at the code snippet below that demonstrates what I mean: <html> <head> <style> body { height: 100%; margin: 0; padding: 0; ...