Draggable shape using Three.js

I have been studying the code for a draggable cube from this link.

However, I am struggling to understand the purpose of creating an offset between the plane and the selected object, as seen in this section of the code:

function onDocumentMouseDown( event ) {

            event.preventDefault();

            var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
            projector.unprojectVector( vector, camera );

            var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

            var intersects = raycaster.intersectObjects( objects );

            if ( intersects.length > 0 ) {

                controls.enabled = false;

                SELECTED = intersects[ 0 ].object;

                var intersects = raycaster.intersectObject( plane );
                offset.copy( intersects[ 0 ].point ).sub( plane.position );// OFFSET

                container.style.cursor = 'move';

            }

        }

Answer №1

When objects move, their coordinates are calculated based on the coordinates where the mouse was initially clicked on the plane, causing a shift. However, this offset can be eliminated:

function trackMouseMovement( event ) {

    ...if ( SELECTED ) {

       var intersection = raycaster.intersectObject( plane );
       SELECTED.position.copy( intersection[ 0 ].point );

   }
}

Give it a try and notice the difference. You can also refer to this example for more information. Keep an eye on the console for messages.

<script src="js/controls/EventsControls.js"></script>

EventsControls = new EventsControls( camera, renderer.domElement );

EventsControls1.attachEvent( 'dragAndDrop', function () {

    this.container.style.cursor = 'move';
    this.focused.position.y = this.previous.y;

});

var object = new THREE.Mesh( geometry, material );
scene.add( object ); 

EventsControls.attach( object );

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

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

myObject loop not functioning properly in Internet Explorer version 10

Could someone please point out what is wrong with this code snippet? HTML: <div id="res"></div> Javascript: var myObject = { "a" : { src : "someimagepath_a.png" }, "b" : { src : "someimagepath_b.png" }, }; va ...

What is the best way to load a database URL asynchronously and establish a database connection prior to the initialization of an Express

My express.js app is set up to run on AWS lambda, with the database URL stored and encrypted in Amazon KMS. To access the URL, decryption using the AWS KMS service is required. // imports import mongoose from 'mongoose'; import serverless from & ...

Developing a concealed Repeater element that is retained in the source code for utilization in JavaScript tasks

I am currently working on a setup with two repeaters: one that is displayed when the page first loads, and another that I want to keep hidden until a link called "Add Stuff" is clicked. My goal is to use JavaScript to make this second repeater visible upon ...

Checking for the presence of the key name "item[]" within an object in AngularJs

I currently have an object called "obj" with two keys: "goal" and "item[]". It looks like this: var obj = {goal:"abc",item[]:"def"}; These keys and values are dynamically generated. Now here's the problem - I need to determine if these keys exist ...

Performing two API calls using Jquery to fetch distinct dynamic elements within two nested $.each loops

There's an API link that contains crucial data about phone brands. From this initial data, I have to create a second API call for each brand to gather more detailed information. For example, the first JSON file (urlphonebrands) lists 3 phone brands - ...

Encountering a 'oembed is null' error in the firebug console while using JQUERY OEMBED

There seems to be an issue with oembed causing an error message in firebug's console window. Specifically, the error is displayed as: oembed is null oembedContainer.html(oembed.code); This error occurs when clicking on a link that leads to the jquer ...

Retrieving the Top 10 Values from a JSON Data Set

Take a look at this snippet from my JSON data. [ {"Element":"Water","Value":20}, {"Element":"Fire","Value":30}, {"Element":"Earth","Value":40}, {"Element":"Air","Value":50}, {"Element":"Spirit","Value":60}, {"Element":"Sun","Value":100}, { ...

Customize Monaco Editor: Implementing Read-Only Sections

I am currently working on setting up the Monaco Editor so that specific sections of the text content are read-only. Specifically, I want the first and last lines to be read-only. See example below: public something(someArgument) { // This line is read-onl ...

Vue: The enigmatic world of ghost properties?

During my project work, I encountered the following code snippet: Main component - <ParameterModal>: <template> <modal-wrapper props="..."> <!-- ... other similar templates are present... --> <template v-else-if="moda ...

The Angular application will only display updated dynamic content upon refreshing the page

I am utilizing a factory to access my server-side data, using $routeParams to pass the id in the server request. Initially, everything functions correctly, but issues arise after the first run through the program. Here is a snippet of my code: Controller: ...

What is the best way to add a data value to a dynamically generated div element?

I've been struggling to link a data value with a dynamically created div, but so far I haven't had any success. I've searched online for solutions, but I can't find any examples that fit my specific issue. If anyone has any advice, I wo ...

The node server.js encountered an error - Module not found

After attempting to start my node server using the following command: node server.js An error was thrown: internal/modules/cjs/loader.js:905 throw err; ^ Error: Cannot find module 'fcc-express-bground' Does anyone have any solutions? ...

Box2dweb: Interaction Point of Collision

Currently working with box2dweb for a game development project. Need assistance in determining the contact point between a "Circle" and "Box". Aware that this can be achieved through b2ContactListener and the Post-Solve Event. Seeking guidance on impleme ...

Laravel's blade allows you to easily convert an HTML element to an array using the same name

I have two separate divs with similar content but different values <div id="tracks-1"> <div> <label>Song Title</label> <input type="text" name="tracks[song_title]" value=""> <input type="text ...

Is the NodeJS rmdir function experiencing issues specific to LINUX?

Currently, I have a NodeJS script section that runs on my Windows 10 machine with the latest Node version and another version on my CentOS8 Linux webserver. The code executes as expected on Windows but throws an error when running on Linux at this specific ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Upcoming JWT authentication module

I've been working on a simple application using next.js and integrating JWT for user authentication. My goal is to have a single navbar and layout that can dynamically adjust based on the authentication status. Below is my code: import React from "r ...