Learn the technique of rotating a line around its endpoint using DragControls in three.js

I made a custom modification to DragControls.js so that it only allows movement of the line on the y-axis.

Here is the line setup I am using:

material = new THREE.LineBasicMaterial( { color: 0xFF0000 } );
geometry.vertices.push(new THREE.Vector3( 0, 0, 0) );
geometry.vertices.push(new THREE.Vector3( 10, 0, 0) );
scene.add( redline );
dragControls = new THREE.DragControls( objects, camera, renderer.domElement );

Below is my revised version of Dragcontrols.js where I added constraints to limit movement:

this.constrains = function(xyz) {

    if (xyz === undefined)
        xyz = 'xyz';

    moveX = moveY = moveZ = false;

    if (xyz.indexOf('x') > -1) {
        moveX = true;
    }

    if (xyz.indexOf('y') > -1) {
        moveY = true;
    }

    if (xyz.indexOf('z') > -1) {
        moveZ = true;
    }

    return this;

};

This is how I implement it in the onDocumentMouseMove(event):

if ( _selected && scope.enabled ) {
        if (event.altKey === true) {
            rotationDrag = true;
        }
        
//TODO: insert rotationDrag check here and rotate the line instead of moving
        
        if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {

            /**
             *  Constrain feature added
             */

            _intersection.sub( _offset );

            if (!rotationDrag) {
                if (moveX) _selected.position.x = _intersection.x;
                if (moveY) _selected.position.y = _intersection.y;
                if (moveZ) _selected.position.z = _intersection.z;
            } else {
                debugger;
            }
        }

        scope.dispatchEvent( { type: 'drag', object: _selected } );

        return;

    }

At the point where the debugger is placed, I aim to have the left end of the line move along the y-axis when altKey is pressed while keeping the right endpoint fixed in X and Y coordinates. This creates a rotational movement similar to a clock's hand.

Any suggestions on how to achieve this effect?

Answer №1

The solution is quite straightforward - determining the angle and directions is the key.

         if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {

            /**
             *  Additional constraint feature included
             */

            _intersection.sub( _offset );
            //_selected.position.copy( _intersection.sub( _offset ) );
            if (!rotationDrag) {
                if (moveX) _selected.position.x = _intersection.x;
                if (moveY) _selected.position.y = _intersection.y;
                if (moveZ) _selected.position.z = _intersection.z;
            } else {
                _selected.rotateZ();
            }
        }

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

The height of divs spontaneously changes after resizing without any instructions

I am developing a jQuery function to vertically center an element. The function is triggered on load and here is the code: JQuery var $window_height; function Centerize(content) { content.css('margin-top', (($window_height - content.height( ...

Leveraging the capabilities of the Freshdesk API

Has anyone had any experience utilizing the FRESHDESK API specifically for creating tickets? The documentation states the following: Request URL: domain_URL/helpdesk/tickets.xml Request method: POST <helpdesk_ticket> <description>Disk fai ...

Modifying a $scope variable beyond the controller in AngularJS

I am trying to update a variable called $scope.outsidescope outside of the controller in my AngularJS application. The routing is done using $routeProvider, and the $scope.outsidescope variable is located outside of the ng-view. My query is how can I modi ...

A guide on executing a double click action on an element in Selenium Webdriver with JavaScript specifically for Safari users

Having trouble double clicking an element in Safari using Java / Webdriver 2.48. All tests work fine on IE, Chrome, and Firefox but Safari does not support Actions. Currently attempting: executor.executeScript("arguments[0].dblclick();", element); or ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

The attempt to compress the code in the file from './node_modules/num2persian' using num2persian was unsuccessful

I have been using the num2persian library to convert numbers into Persian characters. However, whenever I run the command npm run build, I encounter the following error: An error occurred while trying to minimize the code in this file: ./node_modules/num ...

Issue with Angular JS orderBy when sorting by numerical fields is not functioning as expected

Within my controller, I implemented code to convert the rank into a Float data type. details.rank = ''; $scope.order = function (predicate) { $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; if (predicate == & ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

Creating a regular expression to capture a numerical value enclosed by different characters:

export interface ValueParserResult { value: number, error: string } interface subParseResult { result: (string | number) [], error: string } class ValueParser { parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParse ...

Troubleshooting issues with JSON compatibility within the OnChange event

Initially, I wrote this code to retrieve a single data point. However, I realized that I needed more fields returned when the drop-down select menu triggered an onchange event. So, I switched to using JSON, but now it's not returning any data. The dro ...

Error: When attempting to overwrite res.render, a TypeError occurs because the property 'app' is being read from an undefined source

I am working on a project where I need to modify the behavior of the res.render method in order to consistently include an additional option, regardless of any other options present. However, when attempting to implement this modification, I encounter th ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Error encountered while using Chart.js with JSON dataset

Struggling to make this work... Here are the necessary scripts: <script src="Chart.js"></script> <script src="jquery-1.11.3.min.js"></script> This is the full code I am working with: <body> <div id="chartCanvas"> &l ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

What are the steps for adding a JSON file to a GitHub repository?

Could someone lend a hand with my GitHub issue? I recently uploaded my website to a GitHub repository. The problem I'm facing is that I have a JSON file containing translations that are being processed in JavaScript locally, and everything works fine ...

Step by step guide on inserting a message (memo/sticky note) onto an HTML page

Wondering how to accomplish this: I've designed an HTML5 homepage and I'm looking to display a message to visitors, such as "Dear visitor, I am currently on vacation from....", in the form of a memo or sticky note positioned in the top right cor ...

How to use JQuery to parse an external JSON file with array elements in Javascript

My goal is to extract information from an external JSON file using JavaScript, specifically an array and other elements. The JSON file I am working with is called 'TotalUsers.json' {"@version":"1.0", "@generatedDate":"12/20/10 5:24 PM", "day":[{ ...

Utilizing NGRX reducers with a common state object

Looking for a solution with two reducers: export function reducer1(state: State = initialState,: Actions1.Actions1); export function reducer2(state: State = initialState,: Actions2.Actions1); What I want is for both reducers to affect the same state objec ...

What is causing this setInterval function to run repeatedly?

Below is the code snippet from my Vue application: mounted: function () { this.timer = setInterval(async () => { if (this.progress >= 1) { this.progress = 1 clearInterval(this.timer) } console.log('update& ...