Smoothly rotating an object in Three.js with a custom function

I successfully created a Rubik's Cube using Three.js, and everything is functioning as intended. However, I would like to add an animation when turning the cube instead of it snapping into place instantly. How can I achieve a smoother turning effect?

Below is the code snippet that I am currently using:

function turnOrangeSide(inverse) {
    let x = 0;
    let y = 1;
    let z = 1;
    orangeGroup = new THREE.Object3D();
    scene.add(orangeGroup);

    // The following lines group all parts of the Cube that need to be turned.
    orangeGroup.attach(getIntersecting(rotationPointO, x, y, z + 1));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y, z - 1));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y + 1, z));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y - 1, z));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y + 1, z + 1));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y - 1, z + 1));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y + 1, z - 1));
    orangeGroup.attach(getIntersecting(rotationPointO, x, y - 1, z - 1));

    let rotation = Math.PI / 2
    if (inverse) rotation = -Math.PI / 2
    orangeGroup.rotation.x += rotation;
}

You can view a live example here.

Answer №1

One way to achieve a rotation effect on a cube is by utilizing a parametric equation and gradually rotating it around an axis. Here's an example implementation:

let fps = 60;           // frames per second
let duration = 2;       // 2 seconds
const step = 1 / (duration * fps);  // step per frame
const finalAngle = Math.PI/2;
const angleStep = finalAngle * step;
let time = 0;

function animateCube(time){
   if (time >= 1) return; // Animation completed
   time += step;  // Increment time
   cube.rotation.x += angleStep; // Rotate the cube
   requestAnimationFrame(() => animateCube(time));
}

animateCube(time);

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

Triggering an Ajax call for form validation only occurs when the form is not validated

I am struggling with a simple form that has an Ajax call, but the ajax call gets executed even if the form is not validated. In the code snippet below, the line console.log("This line should execute only if Form is validated"); gets executed when the form ...

Large data sets may cause the Highchart Bar to not display properly

Currently, I am working on a web project that displays traffic usage in chart mode using Highchart Bar. The issue I am facing is that there are no errors thrown when running this code. <script type="text/javascript"> $(function () { $(&apos ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Challenges Associated with Promises in JavaScript

I'm having trouble with the last line of code in my program and I need some help figuring out how to fix it. Specifically, I know that the second "then" statement needs to return resolve() but I'm not sure how to go about implementing this. Any t ...

There appears to be an issue with the functionality of the external CSS pathway

placeholder image hereplaceholder image hereplaceholder image here I'm encountering a problem and struggling to identify the mistake in my current approach. ...

Using a Javascript array within a Bootstrap carousel allows for dynamic content to

I am looking to incorporate my javascript array into a bootstrap carousel so that the carousel can display all the elements from the array and determine which picture should be shown based on the data. I also want it to display the title, subtitle, and alt ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

only one of the ng-bind-html elements on the page is functioning

I am currently working on an AngularJS application and encountered a problem with this block of code. Only the first ng-bind-html works for me: <div ng-bind-html='newsTitle'> <div ng-bind-html='newsDetail'></div> &l ...

JavaScript toggle display function not functioning properly when clicked

I've been attempting to create a drop-down list using HTML and JavaScript, but for some inexplicable reason, it's just not functioning as expected despite scouring through countless tutorials on YouTube. Below is the snippet of code that I'm ...

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

Firefox compatibility issue caused by jQuery's appendTo function disrupting hyperlink functionality

I've successfully implemented the material design ripple effect using jQuery, which functions well in IE11 and Chrome 46. However, I've encountered an issue in Firefox 39 where applying the effect to links prevents redirection. Upon investigation ...

"Implementing a select value in React.js using option values and mapping through iterations, with the

Currently, I am working on a React application where I encountered an issue with the map method during iteration. I have a select box that needs to be filled with numbers ranging from 0 to a specified value. My expected output should be [{label:0,value:0 ...

Is there a way to include custom headers in the response of socket.io using express.js?

I have been attempting to override the CORS policy using the following code block: app.use('/\*', function (req, res, next) { res.header("Access-Control-Allow-Origin","*") res.header("Access-Control-Allow-Hea ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Checking for mobile SSR in a ReactJS applicationUncover the signs of mobile

I recently integrated the mobile-detect library into my project following this informative tutorial: link /src/utiles/isMobile.tsx: import MobileDetect from "mobile-detect"; import { GetServerSidePropsContext } from "next"; export co ...

Strategies for organizing your week with a calendar

Hello, I am working on creating a weekly calendar using PHP and I want to add events to the calendar like in this example. However, I am unsure how to display the events in the calendar at the correct time of day. Here is the code snippet I am currently u ...

What is the best way to implement client-side shopping cart calculations using jQuery?

https://i.stack.imgur.com/aOajr.png Here is the content of my shopping cart. Below, I will explain the flow. [product image clicked] -> ajax request fetches details from database for that particular product id and appends (product name,id and price ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...