Limiting drag and drop in Three.js with specified distance thresholds

Is there a way to restrict the distance an object can be dragged and dropped in Three.js using DragControl? I am looking to set a maximum distance from the object's original position to prevent users from dragging it too far.

Answer №1

If you want to add new event listeners in DragControls, you can follow the example provided in the code snippet below. This code showcases a method to reset an object to its original position if the distance between the initial and final vectors exceeds a certain threshold represented by maxDistance

const dragControls = new DragControls(objects, camera, renderer.domElement)
  
// Define variables to store the initial vector and the selected object
let startPos
let selected
// Define the maximum allowed distance between the initial and final vectors
const maxDistance = 500
  
// Check the vector difference upon mouseup event
renderer.domElement.addEventListener("mouseup", function() {
    if (selected && startPos) {
        console.log('distance', Math.abs(startPos.distanceTo(selected.position)))
        if (Math.abs(startPos.distanceTo(selected.position)) > maxDistance) {
            selected.position.copy(startPos)
        }
    }
    selected = null
});
  
// Set the initial vector and selected object on mousedown event
renderer.domElement.addEventListener("mousedown", function(event) {
    event.preventDefault();

    var rect = renderer.domElement.getBoundingClientRect();
    const mouse = new THREE.Vector2()
    mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
    const raycaster = new THREE.Raycaster()
    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(objects);
    if(intersects.length > 0) {
        selected = intersects[0].object;
        startPos = new THREE.Vector3(selected.position.x, selected.position.y, selected.position.z)
        console.log('startPos',{...startPos})
    }
});

DragControls is a straightforward library (consisting of just one class, visit https://github.com/jbyte/three-dragcontrols for more information). In your project, you may consider re-implementing the class and incorporating startPos and maxDistance as properties. By doing so, you can achieve a cleaner and more reusable implementation without the need for additional event listeners and global variables as shown above.

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

Calculating the time difference in days, hours, minutes, and seconds between two UNIX timestamps

I have a special occasion coming up, and the date and time for this event are stored in a Unix timestamp format. Instead of relying on a plugin like modern.js, I am trying to figure out the time difference between today's date and the event date usin ...

What are the steps to rectify the issue of displaying data accurately on

I am working on my ReactJS project and using devextreme to create a unique circular gauge. However, I'm facing an issue where certain values are not being displayed correctly. For instance, instead of showing the value 5011480286.78, it is displaying ...

QuickFit, the jQuery plugin, automatically adjusts the size of text that is too large

I have incorporated the QuickFit library into my website to automatically resize text. However, I am running into an issue where the text is exceeding the boundaries of its containing div with a fixed size. This is something I need to rectify. This is ho ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Rendering Local HTML with local styling and scripts in React Native Webview

I am having trouble loading a local HTML, CSS, and JS file in my React Native webview. The CSS is not being applied to the HTML. Here is my folder structure: https://i.sstatic.net/mqYT9.png My HTML file, along with CSS, images, and JS file are all placed ...

Harness the power of AngularJS by crafting your unique

Hey there! I'm having a bit of trouble figuring out why this isn't showing up. Both View1.html and View2.html are in the partials folder, so that's not the issue. Sometimes the screen is completely blank, other times I only see a Name: label ...

The React-Toastify module is missing

Having issues with react toast plugin displaying an error. Prior to attempting to use the toast feature, I executed this command: npm install --save react-toastify The following error is being shown in Google Chrome Console: ERROR in ./src/Pages/Login ...

What techniques can be employed to utilize multiple JavaScript files?

Hey there, I am facing an issue while trying to execute multiple JavaScript codes. My first script is running smoothly with the change function, but the second one seems to be causing some trouble. Can anyone guide me on how to effectively run multiple J ...

"Can you please provide guidance on accessing the current value of Ref in react-native

I have exhausted all options provided in this URL: How to extract values from input types using this.refs in reactjs? From ref.current.value to ref.value to ref._getText(), everything returns as undefined. After inspecting the JSON output of the ref objec ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

Will the identifier "id" be considered unique if the element with the matching id has its display property set to "none"?

Imagine you have a DIV element in your document with the id "row". Now, if you add another DIV with the same id and change the display property of the first DIV to "none", does the id of the second DIV become unique? ...

Error in Bootstrap table implementation leading to truncation of tbody height due to data-detail-view property

I'm currently working on integrating Bootstrap-Table's detailView feature into my project. However, when I enable data-detail-view="true" for my table, the height of the table element shrinks to 0. Strangely, clicking on any column with ...

What is the best way to terminate all occurrences of three.js once the script has completed running?

I am seeking a way to properly halt all instances of three.js once my script has completed. Is there a universal method like THREE.quit() for this purpose? I find it inefficient to individually remove renderers, composers, cameras, scenes, meshes, backgrou ...

Using a Javascript plugin in Laravel with Vue by importing it into the project

Currently, I am in the process of creating a Vue component by utilizing the functionalities provided by the JavaScript plugin known as Cropper JS. The application is developed using Laravel 5.6. Initially, I installed Cropper JS via NPM: npm install cropp ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Conceal the div element if the value exceeds 0

I'm looking for a way to display a div when the number of remaining days is less than 0. I got it working on jsfiddle, but for some reason, it doesn't work anywhere else. if ($('.daysrem&a ...

Adjust the sidebar size in Bootstrap 5 to align perfectly with the navbar brand

https://i.stack.imgur.com/Ra0c7.png I'm trying to ensure that the width of the sidebar on this page aligns consistently with the end of the logo in the top right. However, using variations of col-xxl-1 etc. is causing inconsistent sizes at different ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...