What is the best approach to smoothly rotate a cube by 90 degrees in three.js?

Currently, when I rotate the cube using key 'a', 'w', 'd', or 's', the rotation is instant. However, I would like to create a smoother rotating motion so that the user can see the cube twisting gradually, instead of the sides changing color abruptly.

Is there a way to make the cube rotate slowly?

The following code demonstrates how I am currently implementing the rotation of the cube:

boxWidth = 1;
boxHeight = 1;
boxDepth = 1;

const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

const materials = [
  new THREE.MeshBasicMaterial({color: 0x0000ff}),
  new THREE.MeshBasicMaterial({color: 0xffffff}),
  new THREE.MeshBasicMaterial({color: 0xffff00}),
  new THREE.MeshBasicMaterial({color: 0x008000}),
  new THREE.MeshBasicMaterial({color: 0xffa500}),
  new THREE.MeshBasicMaterial({color: 0xff0000}),
]

const cube = new THREE.Mesh(geometry, materials);

function onDocumentKeyDown(event) {
  console.log(event);
  if (event.keyCode == 87) { // w button
      cube.rotateX(Math.PI / 2);
  } else if (event.keyCode == 83) { // s button
      cube.rotateX(-Math.PI / 2); 
  } else if (event.keyCode == 65) { // a button
      cube.rotateY(-Math.PI / 2); 
  } else if (event.keyCode == 68) { // d button
      cube.rotateY(Math.PI / 2);
  }
};

document.addEventListener("keydown", onDocumentKeyDown, false);

Answer №1

To smoothly animate a change in orientation from one position to another, you can utilize the Quaternion.rotateTowards() method.

In order to implement this method effectively, you will need to specify both a starting and target orientation, along with an angular step that dictates the speed at which your object rotates. The provided link showcases a brief example demonstrating how to use this method. The crucial code snippet can be found within the animate() function:

const delta = clock.getDelta();

if ( ! mesh.quaternion.equals( targetQuaternion ) ) {

    const step = speed * delta;
    mesh.quaternion.rotateTowards( targetQuaternion, step );

}

The functionality of this code is straightforward: it continuously transitions the object's orientation towards the specified target until they align perfectly.

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 for integrating a logo into router view animations

How can I incorporate a logo into the white fade-in screen that appears when navigating between subpages using <router-view> within App.vue? Here is a simplified version of my App.vue code: <template> <div id="app"> <div ...

The small device screen in Bootstrap 4.5 is experiencing an issue where two rows are overlapping

I recently started learning Bootstrap and encountered an issue. When resizing the browser screen to a smaller size, I noticed that the rows within separate containers were overlapping. Screenshots have been provided for reference. Can someone please guide ...

Is it possible to modify the collection name while saving data in MongoDB?

Is it possible to change the name of the collection where I store the data? I have a Game model and currently save data like this: const teamData = new Game({ id: id, homeTeamName: hTeam, awayTeamName: aTeam, homeTeamGoals: ...

Stop the annoying automatic page refreshing in your Angular single-page application

My Angular routing is set up with HTML5 mode in the following way: app.config($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider.when("/", { templateUrl: "/views/login.html" }).when("/dashboard", { templa ...

Securing Javascript variables from tampering during server submissions - a comprehensive guide

Currently, I am working on developing a basic MVC application in ASP .NET where I want to store all session user data on the client side. This means that every time the page is loaded, the variables reset to zero (e.g., points in a game). The intention is ...

I would like to know how to create a dropdown menu that shows the country name, flag, and code based on the

I have successfully generated the telephone input field. One requirement is to display the Country flag along with the country name as soon as the dropdown is selected. Another requirement is that once the country is selected, it should display the countr ...

JavaScript allows for the creation of animated or timed text

Here is the code snippet I am currently working with: function list() { return "blob1<br>blob2<br>blob3"; } When I run this code, it simply displays all the text in return at once when the function is called. I am wondering if there is a ...

Can you suggest the optimal setup for (javascript SOAP)?

As part of my nightly maintenance process on a LAMP server, I need to retrieve data from a web service using SOAP, which is then applied to a database. While researching various options, I have become overwhelmed by the abundance of information available. ...

Encountering an error in Angular Chosen where the forEach function is not recognized

Implementing Angular Chosen for a multi-select dropdown menu to choose nationalities. https://github.com/localytics/angular-chosen An error message is popping up saying: "a.forEach is not a function" This error seems to occur regardless of whether one, ...

Encountering a "module resolution failed" flow error while attempting to import node modules

After experiencing numerous errors with node modules in my flow configuration, I decided to add the following rule to ignore them: [ignore] .*/node_modules/.* While this fixed the previous errors, it created a new issue. Every time I import a module, I e ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

Disappear gradually within the click event function

I have a coding dilemma that I can't seem to solve. My code displays a question when clicked and also shows the answer for a set period of time. Everything works perfectly fine without the fadeOut function in the code. However, as soon as I add the fa ...

Retrieve the values of a function using the Firebase database

Hey, I'm in a bit of a pickle trying to retrieve the values returned by my function. I can see them just fine in the console log, but how do I actually access them when calling the function? function getprofile(useruid) { return firebase.database ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

Canvas rendering issue in Internet Explorer and lagging problem in Firefox

As a newcomer to Three.js, I have successfully created what I needed using CanvasRenderer. However, I am facing issues with the code not functioning properly in IE and experiencing lag in FireFox. It's no surprise that IE always seems to have some so ...

Transform an array of strings into properties of an object

Looking for a way to map an array to a state object in React? Here's an example: const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"] Assuming you have the following initial state: state = { options:{} } You can achieve ...

Is there a way to utilize OpenLayers to showcase various icons for distinct features all within one layer?

Being new to Openlayers/JS and fairly inexperienced with programming in general, there may be other issues in my code that I'm unaware of. I am currently using the latest version of Openlayers (5.3.0). My application sends GeoJson formatted data via ...

Encountering issue with Konva/Vue-Konva: receiving a TypeError at client.js line 227 stating that Konva.Layer is not a

I am integrating Konva/Vue-Konva into my Nuxtjs project to create a drawing feature where users can freely draw rectangles on the canvas by clicking the Add Node button. However, I encountered an error: client.js:227 TypeError: Konva.Layer is not a constr ...

Creating validation for a custom HtmlInputElement in an HTML form

I am interested in developing a unique input element with its own custom template, and I want the standard HTML <form> to treat it just like any other native input element. Specifically, I would like the browser to validate my custom element when it ...