The focal point of a Three JS rotation

My goal is to rotate the geometry around a pivot point and set that as the new definition of the geometry. I want the current rotationZ to become the new rotationZ 0 without having to keep editing the rotationZ.

This way, when I create a new rotation task, it will start from the updated pivot point and radian value.

I attempted the following solution, but the rotation point ends up moving:

// Add cube for calculations
var box = new THREE.Box3().setFromObject( o );
var size = box.getSize();
var offsetZ = size.z / 2;

o.geometry.translate(0, -offsetZ, 0)

// Perform rotation
o.rotateZ(CalcUtils.degreeToRad(degree));

o.geometry.translate(0, offsetZ, 0)

I also experimented with adding a Group, rotating the group, and then removing it. However, I need to retain the rotation without additional objects. This is the code snippet I came up with:

var box = new THREE.Box3().setFromObject( o );
    var size = box.size();

    var geometry = new THREE.BoxGeometry( 20, 20, 20 );
    var material = new THREE.MeshBasicMaterial( { color: 0xcc0000 } );

    var cube = new THREE.Mesh( geometry, material );

    cube.position.x = o.position.x;
    cube.position.y = 0; // Height / 2
    cube.position.z = -size.z / 2;

    o.position.x = 0;
    o.position.y = 0;
    o.position.z = size.z / 2;

    cube.add(o);

    scene.add(cube);

    // Perform rotation
    cube.rotateY(CalcUtils.degreeToRad(degree));

    // Remove cube and revert to single object
    var position = o.getWorldPosition();

    scene.add(o)
    scene.remove(cube);
    console.log(o);

    o.position.x = position.x;
    o.position.y = position.y;
    o.position.z = position.z;

Therefore, my question is how can I preserve the current rotation as the new 0 rotation point and finalize the rotation?

EDIT I have provided an image depicting my objective. The green object represents the geometry. There is a world origin point (black), an object origin point (red), and a rotation point (blue).

How can I effectively rotate the object around the blue point depicted in the image?

https://i.sstatic.net/q6tg6.png

Answer â„–1

My advice would be to avoid updating the vertices directly, as it may lead to issues with the normals unless you also update them accordingly. It can become quite cumbersome to manage an action that could easily be achieved using transformation matrices.

You were heading in the right direction by applying translation, rotation, and reverse translation. There are predefined methods that can simplify this process significantly.

// obj - object being manipulated (THREE.Object3D or similar)
// point - pivot point for rotation (THREE.Vector3)
// axis - rotation axis (normalized THREE.Vector3)
// theta - angle of rotation in radians
// pointIsWorld - indicates if the point is in world coordinates (default = false)
function rotateAroundPoint(obj, point, axis, theta, pointIsWorld = false){
  
    if(pointIsWorld){
        obj.parent.localToWorld(obj.position); // adjust for world coordinates
    }
  
    obj.position.sub(point); // eliminate offset
    obj.position.applyAxisAngle(axis, theta); // rotate the POSITION
    obj.position.add(point); // add back the offset
  
    if(pointIsWorld){
        obj.parent.worldToLocal(obj.position); // revert from world coordinates adjustment
    }
  
    obj.rotateOnAxis(axis, theta); // rotate the OBJECT
}

Upon completion of this method, the rotation/position changes will be retained. Subsequent calls will transform the object based on the new inputs provided.

Note the adjustment for world coordinates usage. This feature allows seamless transition between world and local coordinate systems by converting the object's position vector appropriately. It is advisable to use this approach when dealing with points and objects in different coordinate systems, though personal experiences may vary.

Answer â„–2

If you're looking for a quick way to change the pivot point of an object, one simple solution is to create a group and add the mesh to that group for rotation.

For example:

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube)

https://i.sstatic.net/Vk2Hj.png

By default, the object will rotate around its center point.

cube.rotation.z = Math.PI / 4

https://i.sstatic.net/hAzMb.png

To change the pivot point, create a new group and add the cube to it.

const group = new THREE.Group();
group.add(cube)
scene.add(group)

https://i.sstatic.net/2vi0D.png

Now, adjust the position of the mesh:

cube.position.set(0.5,0.5,0)

https://i.sstatic.net/aHbYl.png

Next, move the group itself:

group.position.set(-0.5, -0.5, 0)

https://i.sstatic.net/jlmBg.png

Finally, use the group to rotate the object from the adjusted pivot point:

group.rotation.z = Math.PI / 4

https://i.sstatic.net/dNoxD.png

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 on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...

Start CSS3 Animation Automatically

I am working on a multi-page website with a slider that includes a CSS3 animation featuring the famous rocket animation. Here is the code snippet I used: #outerspace { position: relative; height: 400px; background: #fff; color: #fff; } di ...

The two-word string is failing to pass through the query string

I've been working on passing multiple values through the query string. So far, I have successfully passed single-word values to a PHP page using jQuery. However, I encountered an issue when trying to pass a user's name like "Vishal Deb" as it onl ...

The Ajax form is failing to send any headers

Whenever I submit my form, the header data doesn't seem to be coming through. Even though I've done this type of submission numerous times (figuratively speaking), there's always a chance that I might be overlooking something. Any ideas? Che ...

Exporting JavaScript formatting in Netbeans is a breeze

Does anyone know how to preserve the formatting for JavaScript in Netbeans 8.1 when exporting? After clicking on the export button and expanding Formatting, I couldn't find any option specifically for JavaScript. I've thought about locating the ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

Having trouble getting two components to return in React

After successfully implementing the Hello World example by returning "Hello" and "world" from two different components, I encountered a problem with my code. In this specific code snippet, I am unable to return the Menubar component, although the Map compo ...

Mongoose search operation coming up with a blank array

Whenever I utilize $search in mongoose, it returns an empty array. Data Model const mongoose = require('mongoose'); const studentSchema = new mongoose.Schema({ name: { type: String }, }); studentSchema.index({ name: 'text' }); con ...

React: Trying to use the map function on an empty array will result in an error

I am currently facing an issue while trying to populate a shopping cart with items. Even though I have initialized the cart as an empty array, I keep encountering the following error: TypeError: cart.map is not a function ProductContext.js:34 addItemToCar ...

Sorting custom data in a Vue data table, prioritizing null values to be displayed

Currently, in my VueJS v-data-table setup, I am facing a challenge with custom sorting functions. The table has both numeric and string columns, with some null values scattered throughout. My goal is to sort the data by placing null values at the end of ea ...

Excessive iterations occurring in JavaScript for loop while traversing an array

After addressing the issues raised in my previous inquiry, I have made significant progress on my project and it is now functioning almost exactly as intended. The main purpose of this website is to iterate through the World Of Tanks API to generate cards ...

Is there a text form in Angular that allows only numerical input?

Here's an input form in Angular that I'm working on: <input ng-model="sc.zip" class="form-control" maxlength="5" type="text" /> I want to keep the form as a simple empty textbox without limiting it to only numbers. However, I do want to r ...

The functionality to redirect in Wordpress Contact Form 7 based on the value of a radio button selection does

For the past 5 hours, I have been diving deep into Contact Form 7 redirects that are based on values. Despite my efforts, I am unable to figure out why my code isn't functioning properly. Is there anyone who can spot the issue? Contact Form Radio But ...

Is the state mutated when using the .map() function to update it?

I am new to working with React and I am still struggling to understand state mutation. After reading multiple posts on this topic, I am finding it difficult to grasp the concept of state mutation. So, I have decided to seek clarification on this matter. ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Why is my res.data returning an array of objects in AngularJs?

I've been working on integrating an API with AngularJS and trying to display the data using ng-repeat, but I'm facing challenges in accessing the object's information. Below is the feedback I received: (20) [{…}, {…}, {…}, {…}, {†...

Utilizing Ajax to dynamically generate unique ID's for multiple checkboxes

I have been working on a website that is almost completed, however, I have come across a new task where I need to select check-boxes in order to archive news items or "blog posts". The concept is to have a check-box next to each blog post and by checking ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

What is the process for updating parameters before finalizing a route in Vue.js?

I have set up a route with a value parameter: routes.push({ name: 'test', path: '/test/:value', component: resolve(__dirname, 'src/pages/test.vue'), }); Now, I want to modify the route so that it also include ...