Rotating around the midpoint of a manipulator in Three.js

Despite asking a similar question recently, I am still struggling to figure out how to properly set the center of a three js control in order for it to rotate as intended. I have come across various examples involving geometry, bounding boxes, pivot points, and matrices, but none of them have provided a clear answer. In my specific case, I am trying to create a Rubik's cube, but the first side is not rotating at the center. I am hopeful that someone can provide guidance on how to set the center of the control so I can achieve the desired rotation effect. Here is a link to my example: http://codepen.io/anon/pen/gMMRKJ (you can rotate the cube by holding down the mouse and moving it).

Here is the code where I am creating the Rubik's cube and the first control (the spinning side):

// Adding all the Rubik's cube elements
        var gpboyw = [];
        gpboyw.push(new THREE.MeshBasicMaterial({ color: green }));
        gpboyw.push(new THREE.MeshBasicMaterial({ color: purple }));
        gpboyw.push(new THREE.MeshBasicMaterial({ color: blue }));
        gpboyw.push(new THREE.MeshBasicMaterial({ color: orange }));
        gpboyw.push(new THREE.MeshBasicMaterial({ color: yellow }));
        gpboyw.push(new THREE.MeshBasicMaterial({ color: white }));

        side1 = new THREE.Object3D();


        for (var x = 0; x < 3; x++) {
            for (var y = 0; y < 3; y++) {
                for (var z = 0; z < 3; z++) {
                    var faceMaterial = new THREE.MeshFaceMaterial(gpboyw);
                    var cubeGeom = new THREE.BoxGeometry(2.9, 2.9, 2.9);
                    var cube = new THREE.Mesh(cubeGeom, faceMaterial);
                    var xp = x * 3 - 3;
                    var yp = y * 3;
                    var zp = z * 3 - 3;
                    cube.position.set(xp,yp,zp)
                    scene.add(cube);
                    if (z === 0) {
                        console.log('x: ' + xp + ' y: ' + yp + ' z: ' + zp);
                        side1.add(cube);
                    }
                }
            }
        }

        scene.add(side1);

However, I am uncertain about how to properly set the center of side1 to ensure that it rotates correctly.

Answer №1

In order to rotate around the center of an object, one can determine the center point by utilizing a bounding box object called THREE.Box3.

For instance, to identify the midpoint of a mesh:

var boundingBox = new THREE.Box3().setFromObject( mesh );
var center = boundingBox.center();

With the center point established, it becomes possible to perform rotations. Hopefully, this approach will assist you in creating a satisfying solution for your Rubik's cube.

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

Uninterrupted jQuery AJAX calls

I have a scenario where I need to periodically update an image on my view using ajax every 10 seconds. Any suggestions on how I can achieve this? Appreciate the help. ...

Plugin for webpack that replaces a specified function with an alternative one

I'm currently working on a webpack plugin that has the ability to analyze code and replace a particular function with another function. Additionally, this plugin will make the new function accessible globally. class PluginName { constructor(local, ...

JavaScript is unable to modify the value of an input in HTML

function modifyComment(id) { var pageID = "<?= $ID ?>"; var commentID = "p" + id; console.log(id); console.log(commentID); console.log(pageID); var commentContent = document.getElementById(commentID).innerHTML; < ...

Can you explain the significance of a single variable line in JavaScript?

While reading a book on Angular.js, I came across the following syntax: $scope.selectedOrder; // What does this syntax mean? $scope.selectOrder = function(order) { $scope.selectedOrder = order; }; I understand that selectedOrder is a property of the $s ...

Embedding the local host into a href link in NextJS

After creating a menu with the Link component in NextJs using href=#contact, I encountered an issue. When I use querySelector on this a element, the href unexpectedly changes to http://localhost:3000/#contact', preventing me from scrolling to that sec ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

Executing a function right away when it run is a trait of a React functional component

Having a fully functional React component with useState hooks, and an array containing five text input fields whose values are stored in the state within an array can be quite challenging. The main issue I am facing is that I need to update the inputfields ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

JSON object name

Here are the specific file locations for loading each of the CSS and JS files. <link href="css/default.css" rel="stylesheet" /> <script src="js/main.js"></script> In XML, the filename is input as shown below ...

What steps are involved in a server utilizing Next.js to create a complete document for transmission to the client?

Understanding Next.js has been quite challenging for me. I am struggling to grasp how it operates on the server and how the server is able to implement server side rendering with the files generated by Next.js during the build process. I have a good under ...

Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to anothe ...

The error message "ReferenceError: window is not defined" occurs when using npm clevertap-react in Next.js

Recently, I embarked on the task of integrating the Web SDK Quick Start Guide from CleverTap into my Next.js application. In my quest for the best approach, I came across packages like clevertap-web-sdk and clevertap-react on npm. Despite following the rec ...

Setting a default value in react-select

Recently, I developed a react-select component that is compatible with redux-form. The SelectInput component looks like this: const MySelect = props => ( <Select {...props} value={props.input.value} onChange={value => props.input.on ...

Tips on submitting JSON data to a server

I need the data to be structured like this {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c3f18121e1613511c1012">[email protected]</a>","password":"1"} but it is currently appearing like this { & ...

Using React Material UI checkboxes: Learn how to manipulate other checkboxes within a group by toggling a single checkbox

I've set up 3 checkboxes - Not Started, In Progress, and Completed - and I want only one to be checked at any given time. If 'Not Started' is initially checked, how can I make it uncheck automatically when I check 'Completed'? Th ...

PrimeFaces Issue with Redirection

Hello everyone, I am currently dealing with a redirection issue. Basically, I have an API that gets triggered when a user clicks on an image. This API captures the user's contact number and initiates a call through the software. Everything is functi ...

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

Using React to redirect a category of components to a specific sub-path, such as transforming "/templates" to "/templates/list"

Having a React app, I'm looking for a way to avoid duplicating the function of redirecting users to /<component>/list in every component if they visit just /<component>. How can this be achieved at a higher level? I have a layout componen ...

CKEditor4 plugins do not function properly when used with multiple instances within Vue Components

After developing a Vue component for rich text editing with CKEditor 4 on my website, I encountered an issue. When the component is first mounted, everything works perfectly including all default plugins. However, if another instance of the same component ...

What is the proper way to address the issue of nesting ternary expressions when it comes to conditionally rendering components?

When using the code below, eslint detects errors: {authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />} Error: Avoid nesting ternary expressions. eslint(no-nested-t ...