What is the method for rotating an object on the world axis in three.js?

Is there a way to perform rotations using the axis of the world rather than the object?

I'm attempting to rotate an object, but I'm finding that after the initial rotation, subsequent rotations are not behaving as expected.

If rotating along the world axis is not an option, my next approach would be to reset the axis after each rotation. Is there a specific function that can help with this?

I've encountered issues when trying to use object.eulerOrder, as it alters the orientation of my object when setting object.eulerOrder="YZX" after multiple rotations.

Answer №1

UPDATED: VERSION 0.125.2

DEMONSTRATION: codesandbox.io

const THREE = require("three");

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.z = 5;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(1, 1, 1, 4, 4, 4);
const material = new THREE.MeshBasicMaterial({
  color: 0xaf49bd,
  wireframe: true
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// specify the Z-axis in the global coordinate system
const axisZ = new THREE.Vector3(0, 0, 1);
// rotate the object by 45 degrees around this axis
cube.rotateOnWorldAxis(axisZ, THREE.Math.degToRad(45));

function animate() {
  // rotate the object on its Y axis,
  // considering that the cube has been previously tilted at a 45-degree angle.
  cube.rotation.y += 0.008;
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

animate();

Answer №2

Here's a slight modification, tested using version r56.

THREE.Object3D._matrixAux = new THREE.Matrix4(); // global auxiliary variable
// Caution: 1) axis is assumed to be normalized.
//  2) matrix must be updated. If not, call object.updateMatrix() first
//  3) this assumes we are not utilizing quaternions
THREE.Object3D.prototype.rotateAroundWorldAxis = function(axis, radians) { 
    THREE.Object3D._matrixAux.makeRotationAxis(axis, radians);
    this.matrix.multiplyMatrices(THREE.Object3D._matrixAux,this.matrix); // r56
    THREE.Object3D._matrixAux.extractRotation(this.matrix);
    this.rotation.setEulerFromRotationMatrix(THREE.Object3D._matrixAux, this.eulerOrder ); 
    this.position.getPositionFromMatrix( this.matrix );
}
THREE.Object3D.prototype.rotateAroundWorldAxisX = function(radians) { 
    this._vector.set(1,0,0);
    this.rotateAroundWorldAxis(this._vector,radians);
}
THREE.Object3D.prototype.rotateAroundWorldAxisY = function(radians) { 
    this._vector.set(0,1,0);
    this.rotateAroundWorldAxis(this._vector,radians);
}
THREE.Object3D.prototype.rotateAroundWorldAxisZ = function(degrees){ 
    this._vector.set(0,0,1);
    this.rotateAroundWorldAxis(this._vector,degrees);
}

The last three lines serve to synchronize the parameters (position,rotation) with the matrix... I am curious if there exists a more efficient approach for this...

Answer №3

Once you reach level 59, this task becomes much simpler (spin around the x-axis):

const calculateRotation = function ( object, rotateX )
{
    const euler = new THREE.Euler( rotateX, 0, 0, 'XYZ' );
    object.position.applyEuler( euler );
}

Answer №4

Updated response by @Neil (tested on r98)

function rotateObject(obj, axis, angle) {
   let rotationMatrix = new THREE.Matrix4();
   rotationMatrix.makeRotationAxis(axis.normalize(), angle);
   rotationMatrix.multiply(obj.matrix);
   obj.matrix = rotationMatrix;
   obj.setRotationFromMatrix(obj.matrix);
}

Answer №5

Hey @acarlon, your answer just saved me from a week of frustration. I've tweaked your function a bit and here are my updated versions. Hopefully, this will spare someone else the 20+ hours I spent trying to solve this.

function rotateObjectAroundAxis( obj3D, axis, angle ){

    var euler;

    if ( axis === "x" ){
        euler = new THREE.Euler( angle, 0, 0, 'XYZ' );      
    }

    if ( axis === "y" ){
        euler = new THREE.Euler( 0, angle, 0, 'XYZ' );              
    }

    if ( axis === "z" ){
        euler = new THREE.Euler( 0, 0, angle, 'XYZ' );      
    }
    obj3D.position.applyEuler( euler );
}

function rotateObjectIn3D( obj3D, angles, order = 'XYZ' ){

   var euler;

   euler = new THREE.Euler( angles.x, angles.y, angles.z, order );

   obj3D.position.applyEuler( euler );

}

This code works like a charm in r91. I hope it comes in handy for you too.

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

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

What is the best way to include a new user in my list of friends within the User schema?

Working on my customized social media platform, I have implemented a feature where users can send friend requests by clicking on a button. <form action="/requests" method="POST"> <input type="hidden" name="send ...

Accessing nested objects within a JavaScript array for an Express API

My current data sample looks like this: var data = [{ articles : [{ id : '0', url : 'foo', title : 'Foo', body : 'some foo bar', category : 'foo', tags : ...

How to Dynamically Retrieve Keys from JSON Array in Javascript

Could you lend me your expertise by answering a query of mine? Here is a JSON array that I currently have: [{"A":20,"B":32,"C":27,"D":30,"E":40}] My goal is to pull out the keys (A, B, C, D, E) from this JSON array rather than the values. While I have m ...

Storing information as variables in jQuery

I'm fairly new to working with Javascript and JQuery, and I've encountered a challenge that I initially thought would be straightforward. My project involves creating a website consisting of a single HTML page, a CSS stylesheet, and a JavaScript ...

Evaluating the generated HTML using JavaScript and Selenium testing

I am a new user of Selenium using C# and I want to automate the login process on a third-party website. When I manually navigate to the page in Chrome and inspect the elements, I can see the text boxes for username and password. <input type="text" id=" ...

Exploring the process of iterating through and organizing a JavaScript array

Recently, I encountered a JavaScript object that was generated by a particular API. The object is structured in a way that it can potentially have multiple instances of the same 'equity' (such as Hitachi Home in this case): { "results": { ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

The Three.js duplication tool replicates all mesh data from the original volume and its associated child nodes

In my quest to generate a 3D model of intricate geometry (specifically nuclear physics particle detectors) using ThreeJS, I encountered a challenging situation. One particular example involves handling around 100,000 geometries and a staggering 4.5 million ...

Updating the image sources of a group of image tags with a predetermined list

Looking to update a series of image source references within a specific div tag. For example: <!-- language-all: lang-html --> <div id="Listofimages"> <img src="images\2page_img_3.jpg"> <img src="images\2page_img_3 ...

transferring a JavaScript variable to PHP upon submitting a form

This question arises after my previous inquiry on the topic of counting the rows in an HTML table using PHP. Since I didn't find a solution that worked for me, I am exploring new methods but struggling with the implementation. My approach involves ass ...

Is JSON.stringify failing to function correctly in Mozilla Firefox?

Currently, I am attempting to convert an object into a string in javascript. After stringifying the object, I have noticed some discrepancies between different browsers. {"jobTypeArray":"[CONTRACT -W2]"} In Firefox and Chrome, the values appear as follow ...

The reset function is malfunctioning on the meteor entity

Currently, I am going through an angular-meteor tutorial that can be found here I seem to be facing some issues with my code. Here's what I have: angular.module('socially').controller('PartyDetailsCtrl', function($scope, $statePa ...

Is there a way to swap out a div with another using ajax and php?

i am looking to update the content from readmore.php into <div id='box'> based on id_pages in index.php after clicking <a class=readmore> Read More </a>. i have been trying to figure out how to retrieve data from readmore.p ...

Guide to incorporating React component with Postgres database

I'm confused about a scenario where I have created a React project with the command npx create-my-app myProject, and within the public folder, there are multiple folders containing NodeJS for a Postgres database. My question is, if I need to access da ...

Tips for preloading an image with Vue's built-in tool

My Vue CLI app contains a feature where a series of images transition when a user clicks a button. The issue arises when the image loading is delayed until the button click, causing a choppy experience as the images suddenly pop in during the transition, d ...

Encountering a problem with fetching data in a dropdown using a hidden select in MVC 4 Razor and Selectpicker

I need to show my hidden select data in dropdown-menu inner selectpicker ul with the default "--choose--" option selected. ASP.NET MVC Razor Syntax @Html.DropDownListFor(model => model.BrandName, Model.CompanyItems, "--Choose Brand--", new { @id = "B ...

What could be the reason for rowsAffected not returning an integer value?

Currently, I am working on executing the SQLite statement in an iOS application. To verify the count of affected records, I have implemented success and error callback methods. Upon receiving the results, although the variables are correctly defined, I en ...

What is the process for building an interactive quiz using JavaScript?

In the process of creating a quiz, I envision a user interface that presents questions in a "card" format. These questions will include simple yes/no inquiries and some multiple-choice options. As the user progresses through the quiz, their answers will de ...

Ways to properly close open HTML tags using node.js?

Have you ever encountered a situation where user-entered content from a database or similar source only contains the opening tag without the closing tag? This can disrupt the layout of your website. Is there a way to fix this issue using Node.js on the s ...