What is the best way to rotate a mesh by 90 degrees in ThreeJS?

Currently, I'm working on rotating a mesh by 90 degrees within Three JS. Below is an image illustrating the current position:

My goal is to have the selected mesh rotated parallel to the larger mesh. I attempted to rotate the matrix using the following code snippet:

matrix =   new THREE.Matrix4().makeRotationX(1.57)

However, this resulted in the mesh undergoing unexpected rotations. Is there a simpler method to rotate it by 90 degrees?

Answer №1

The rotation in three.js is based on Radians, a unit of measurement you're probably familiar with

One way to implement this is:

mesh.rotation.x = Math.PI / 2;

Alternatively, you could try:

mesh.rotation.set(new THREE.Vector3( 0, 0, Math.PI / 2));

Answer №2

If you want to change the orientation of an object, you can achieve this using the following function:

function adjustObjectOrientation(object, rotationX=0, rotationY=0, rotationZ=0) {
   object.rotateX(THREE.Math.degToRad(rotationX));
   object.rotateY(THREE.Math.degToRad(rotationY));
   object.rotateZ(THREE.Math.degToRad(rotationZ));
}

// example of how to use it:
adjustObjectOrientation(myCar, 60, 45, 30);

Answer №3

If you have a variable called objectToSpin that requires a 90 degree rotation in the X axis, you can achieve this by following these steps:

let objectToSpin = new THREE.Object3D(); // Replace Object3D with your specific type of object

// Rotating the object by 90 degrees in the X axis
objectToSpin.rotateX( Math.PI / 2 );

Answer №4

To rotate along the X axis, utilize the rotateX() method

mesh.rotateX(Math.PI / 180 * 90)

For instance, a 1-degree step would be:

Math.PI / 180 = 0.17453292519943295

The result of rotating 90 degrees is:

0.17453292519943295 * 90 = 1.5707963267948966

https://en.wikipedia.org/wiki/Euler_angles

rotateX()
rotateY()
rotateZ()

Answer №5

Experimented with version r96, an alternative method is:

Use the code snippet: mesh.rotation.setFromVector3(new THREE.Vector3( Math.PI / 2, 0, 0));

Answer №6

Calculate the radian equivalent of your angle:

const radian = 2 * Math.PI * (user_angle / 360); //user_angle represents the angle you want to convert to radian, e.g. 90 or 12

Answer №7

If you're looking for an alternative method, you can adjust the quaternion of the mesh like this:

mesh.quaternion.set(0, Math.PI / 2, 0, 0);

For a simpler approach that doesn't interfere with existing values, you can do:

mesh.quaternion.y = Math.PI / 2

Answer №8

My preferred method for rotating objects is by utilizing quaternions.

   function rotateObject( obj, degrees, axis ) 
  {
      // Axis parameter represents a THREE.Vector3
      var quaternion = new THREE.Quaternion();
       quaternion.setFromAxisAngle(axis, THREE.MathUtils.degToRad( degrees ) ); // Radians are required
       quaternion.normalize();
       obj.quaternion.multiply( quaternion );
   }

If I want to rotate an object by 90 degrees along the Z axis, the function call would be

rotateObject( myMesh, 90, new THREE.Vector3( 0, 0, 1 );

For a gradual rotation over time, the slerp method can be used, adjusting the progress parameter from 0 to 1.

function rotateSlerp( obj, degrees, axis, progress )
{
    var quaternion = new THREE.Quaternion();
    quaternion.setFromAxisAngle( axis, THREE.MathUtils.degToRad( degrees ) );
    quaternion.normalize();
    obj.quaternion.slerp( quaternion, progress );
}

To implement this, the function call would be

let progress = 0;

function animateRotation()
{
  progress += 0.05;
  rotateSlerp( myMesh, 90, new THREE.Vector3( 0, 0, 1), progress );
  requestAnimationFrame( animateRotation );
}

   

   

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

How can I find the last element that was selected using XPath in the browser console

Need help with XPath: $x(("//div[@class='ag-header-row']))[1] I'm working with an array of divs, but I want to select the last one. The [1] is necessary due to multiple rows with this class. I’ve heard about using [last()], but unsure w ...

What is the process for detaching and attaching click animations using the on() method?

I am encountering an issue with a recursive loop that executes a simple animation. These animations are controlled by the page load and clicking on controls .carousel_item. Click here for live sample JSFiddles for demonstration purposes Challenge: The pr ...

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

increasing the size of the JSON object

I have a function that is being called multiple times utilizing jQuery to fetch different JSON data from an API. My aim is to calculate the total count of a specific portion of the JSON retrieved. Below is an example of what I currently have: getTheData( ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Node.js - updating the value of a exported integer variable

In my file A.js, I have defined a module-level variable called activeCount and exported it using module.exports. In another file named testA.js, I am attempting to access and modify the value of activeCount. Despite my efforts, changes made to activeCount ...

How much worth does an unfilled text input box hold?

I've been working on integrating a search feature and I'm having an issue with the functionality. Below is the code snippets for both HTML and JS: HTML <form> <input type="text" ng-model="searchVar" class="searchbox"> <in ...

Update the CSS dynamically using JavaScript or AngularJS

Is there a way to dynamically modify this CSS style using JavaScript or in an Angular framework? .ui-grid-row.ui-grid-row-selected > [ui-grid-row] > .ui-grid-cell{ background-color: transparent; color: #0a0; } .ui-grid-cell-focus ...

Is it possible to expand the CORS permissions to the routers directly from the app?

I have a couple of questions: Is it possible to just use cors() once in my server.js instead of having to call and use it in every router file? Can I simply require express once in my server.js without having to call it in all my router files? Currently, ...

The primeVue menubar's active/focused item highlighting feature is not functioning correctly

Currently, we are in the process of developing an electron-based application with the front end primarily coded using Vue.js and primeVue. As a novice, I am encountering issues with the menubar component from primeVue. The problem is that no matter which i ...

Leverage dynamically loaded HTML classes using jQuery

My page has dynamically loaded divs with the class name product. The issue I am facing is that Jquery does not seem to recognize this class when using the code below. Clicking on the product divs doesn't trigger any action, while clicking on nav-eleme ...

Sending forms through the .NET platform

On my .NET page, I have implemented client-side validation for a submit button within the form element. var register = $('#<%= Register.ClientId %>'); register.click(function(){ validation.init(); return false; }); Disabling the f ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

How does the texture's type relate to its format?

I've been working on figuring out how to render volumetric raw data in three.js, specifically dealing with the relationship between texture type and format (in my case, texture3d) in three.js. The available texture types include: https://i.sstatic ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Using Python's Requests library to authenticate on a website using an AJAX JSON POST request

I'm a beginner in Python and struggling to create the correct code for using Python requests to log in to a website. Here is the form code from the website: <form autocomplete="off" class="js-loginFormModal"> <input type="hidden ...

Enhancing Data Tables with Jquery: Implementing Column Filtering for Multiple Elements within Table Cells

I am looking to utilize jQuery datatables for filtering a column that may contain multiple values within a single td. To achieve this, I referenced the example provided in the datatables documentation. In the image below, my goal is to filter the office ...

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

The controller in Angular uses the $scope symbol _

App.controller('todoController', function ($scope) { // create a message to display in our view $scope.todos = [{ name: 'angular', done: false }]; $scope.clearTodo = function () { $scope.todos = _.filter($scope.tod ...