Adding Rotation to a group in Three.js using a pivot point

I'm currently in the process of constructing a Rubik's Cube using Three.js. My method involves grouping all the small cubes that need to be rotated together and then performing the rotation on the group as a whole. To determine the pivot point for the rotation, I came across this useful function:

//Turn Group Around Center function
        THREE.Object3D.prototype.rotateAroundWorldAxis = function () {
            // rotate object around axis in world space (the axis passes through point)
            // axis is assumed to be normalized
            // assumes object does not have a rotated parent
            var q = new THREE.Quaternion();
            return function rotateAroundWorldAxis(point, axis, angle) {
                q.setFromAxisAngle(axis, angle);
                this.applyQuaternion(q);
                this.position.sub(point);
                this.position.applyQuaternion(q);
                this.position.add(point);
                return this;
            }
        }();

While the function works perfectly for a single rotation, it seems to fail when applied multiple times:

myGroup.rotateAroundWorldAxis(rotationPoint, zAxis, Math.PI / 2);
myGroup.rotateAroundWorldAxis(rotationPoint, zAxis, Math.PI / 2);

No additional change occurs during the second rotation.

This issue may be due to the fact that the function only applies a new rotation instead of adding to the existing one. (rotation = 90 rather than rotation += 90)

So, my question is: How can I modify the function to retain previous rotations?

Answer №1

It seems you're facing an issue that could benefit from using quaternions for simplifying rotations.

To illustrate this concept, I've created a tutorial in three.js where I built a small solar system model. In this model, various planets orbit around a sun on different paths. You can view the demo here, and access the code on my GitHub repository. The key function used for planet rotation can be found in main.html:

function animatePlanets() {
            requestAnimationFrame(animatePlanets);
            var quaternion, rotationSpeed, rotationSpeedMoon, pivotPoint, pivotPointMoon, rotationAxeMoon, subgroup, planetPosition, planet

                for ( var i = 0; i < views.length; ++ i ) {

                    var view = views[ i ];
                    var camera = view.camera;

                    for (let i=1;i<group.children.length;i++){

                        // Rotate the planet around the sun
                        pivotPoint = group.children[i]
                        planetPosition = pivotPoint.children[0].position

                        // Defining the rotation axis and speed
                        rotationAxis = (new THREE.Vector3(-planetPosition.y,planetPosition.x,0)).normalize()
                        rotationSpeed = pivotPoint.speed

                        // Applying the rotation to the planet
                        quaternion = new THREE.Quaternion().setFromAxisAngle(rotationAxis,rotationSpeed)
                        pivotPoint.applyQuaternion(quaternion)

                        // Applying local rotation to the planet if not satellites
                        if (pivotPoint.children[0].children.length == 0){
                            planet = pivotPoint.children[0]
                            quaternion =  new THREE.Quaternion().setFromAxisAngle(rotationAxis,rotationSpeed*10)
                            planet.applyQuaternion(quaternion)
                        }
                // Render the scene, using the camera specifications
                renderer.render(scene, view.camera);
                }
            }

I hope this example clarifies the concept for you. Essentially, I establish a rotation point and apply a rotation at a specific speed to each planet within the group around this point.
Feel free to reach out with any further questions!

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

Adaptable design tailored for smartphones

When it comes to developing mobile websites for various platforms such as iPhone 3 and 4, Android, Blackberry Torch, etc., I usually find myself needing to slice images based on the specific platform. The challenge arises from constantly having to slice im ...

Differences between async/await and then methods in React, demonstration shows that only async/await is functional. Why is

Trying to understand and implement two different API data fetching methods in React app development. The first method involves using the JavaScript Fetch API, while the second method utilizes the async/await syntax. I am currently experimenting with both a ...

What is the correlation between statistics and posts that are generated dynamically?

One interesting aspect to consider is how statistics are connected to individual posts. For instance, linking the like count to each Facebook post or tying upvote and downvote stats to a question on Stackoverflow presents some intriguing challenges. How ...

three.js: Panorama viewer shows distorted image

Currently I am immersing myself in the world of three.js and have created a basic panorama viewer: Check it out here Unfortunately, I noticed that the vertical edges of the pillars appear to be rippled in my creation. On the other hand, when using the Pano ...

Discover the magic of Material UI's Multiple Select feature for working with arrays

Utilizing the material-ui multiple select feature, I have set up a demo following the guidelines provided in the Multiple Select documentation. You can check out my example here: codesandbox In my demonstration, I am aiming to use 2 arrays for two separa ...

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

Unable to stop the default action in IE for certain code

I am facing an issue on my website where the JavaScript I have implemented to prevent page reload is not working in Internet Explorer. The code functions properly in all other browsers, except IE. Here is the JavaScript code snippet that should prevent pa ...

Track your status with jQuery technology

I have a link: <a href="/test/number/3/phone/0">33df</a> Is there a way to determine if the words 'number' and 'phone' are present in this link? I am looking for a function similar to: check('number', ' ...

Looping through an array of items in a for loop with a chain of

I want to ensure that the for loop is successfully executed and then the result is passed to the next function: FindIdsRequests = function(){ results = $scope.requests var deferred = $q.defer(); var promise = deferred.promise; var array = ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

How can I clear all jQuery toggled classes that have been added across the entire webpage in an Angular project?

Upon clicking a link within an element, the following CSS is applied: <a class="vehicleinfo avai-vehicle-info-anc-tag" ng-click="vehicleInfo($event)">Vehicle Info <span class="s-icon red-down-arrow"> </span> </a> $scope.vehic ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

How can I implement a jQuery modal dialog that loads a form page with pre-existing jQuery code for Autocomplete functionality?

I am facing an issue where I have a dynamically generated form on a web page and I want to display it using the jQuery UI modal dialog. Previously, I was suggested a solution that worked when my form did not already contain jQuery UI components like Autoc ...

jQuery drag and drop for more than one object

I am in the process of building a web-based file browser using jQuery and PHP. One of the tasks I need to accomplish is the ability to select multiple files/folders and drag them into another folder. My research so far indicates that jQuery UI's drag ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

Utilizing Prototype in Node.js Modules

Currently, I am working on a project involving multiple vendor-specific files in node. These files all follow a similar controller pattern, so it would be more efficient for me to extract them and consolidate them into a single common file. If you're ...

Creating a loop to iterate through JSON data being received

I successfully used JSON to display data, but I am now wondering how I can print all the database entries into a div or table. JavaScript $(document).ready(function() { $.ajax({ type : 'POST', url : 'server.php', dataTyp ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

Utilizing Facebook's JavaScript SDK to transmit variables to PHP using ajax

Thank you in advance for your attention. I am trying to utilize the Facebook js SDK to retrieve the user's name and id, and then send them to PHP on the same page (index.php). After successfully obtaining the username and id and storing them in two Ja ...