Achieve a clockwise rotation of an object back to its original position using Three.js

As a novice in the world of THREE.js, I am currently working on an animation that spins a 3D model around its Y axis. However, for my website project, I need to smoothly rotate it back to its original position within a span of 90 frames. Despite trying different code snippets, I have encountered issues where it only works half the time and messes up the other half, especially after letting it spin for a while.

Below is the current code snippet I am using for the rotation:

//Angle calculation
    angle = ((room.rotation.y * 180) / Math.PI) % 360;
    total_deg = room.rotation.y;

//Lap calculation:
    if(angle > 0) {
        positiv = true;
    } else {
        positiv = false;
    }
    if(angle < last_angle) {
        direction = "down";
    } else {
        direction = "up";
    }
    if(direction == "up" && positiv == true) {
        lap = 1;
    } else if(direction == "down" && positiv == true) {
        lap = 2;
    } else if(direction == "down" && positiv == false) {
        lap = 3;
    } else if(direction == "up" && positiv == false) {
        lap = 4;
    }
    if(last_lap == 4 && lap == 1) {
        room.rotation.y = 0;
    }
    last_angle = ((room.rotation.y * 180) / Math.PI) % 360;

//Reverse rotation based on the current lap

    if(lap == 4) {
        room.rotation.y += -total_deg / 90;
    }
    if(lap == 3) {
        room.rotation.y += -(Math.PI - Math.abs(total_deg)) / 90;
    }
    if(lap == 2) {
        room.rotation.y += (Math.PI - Math.abs(total_deg)) / 90;
    } else {
        room.rotation.y -= total_deg / 90;
    }
//Reset the rotation when the room completes a lap - this fixes some rotation issues although I'm not sure why

    if(last_lap == 4 && lap == 1) {
        room.rotation.y = 0;
    }

I've been struggling with this problem for days now, so any assistance would be greatly appreciated.

Answer №1

It appears that there may be a misunderstanding regarding the use of degrees and radians in your objective. Three.js typically uses radians, but I noticed you have 360 in your code which seems a bit puzzling.

This modified code snippet should align with your intended purpose. It divides 2 pi (representing one full rotation in radians) into 90 frames for smoother animation.

var i = 0;
function update(event) {

// angle
    if (i++ < 90) {
        this.rotation.y += 2 * Math.PI / 90;
    }
    
}

Answer №2

After some experimentation, I managed to solve the problem by utilizing a Quaternion based on the initial rotation of the objects and then applying that rotation later. This particular example provided valuable insights:

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

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

Looking for a way to perform a component query on a grid?

Is there a way to query a grid in an extension window that does not have an id or itemId associated with it? I know how to do it with an id, but is there a way to do it without one? var yourGrid = Ext.ComponentQuery.query('yourGridID')[0]; ...

Is it possible to implement a custom radio tab index without using JavaScript

Is it possible to apply the tabindex attribute on custom radio buttons, hide the actual input element, and use keyboard shortcuts like Tab, Arrow Up, and Arrow Down to change the value? Check out this example on StackBlitz ...

How about exploring a basic example of a button click with the combination of Ajax and Node

Exploring the realms of Ajax and Node.js + Express for the first time, I am currently on a quest to establish communication between the front and back end using buttons. There's a button on an HTML page that I wish to utilize to invoke a function fro ...

Convert a portion of an object into a string to send in a server request

I have customized the fetch method of a Backbone Collection to make a request to a different URL under certain conditions, and I need to include some data with it. The modified fetch method (which I obtained from another solution on Stack Overflow) is as f ...

Having difficulty navigating between Spring MVC and Angular Js components in my project

https://i.sstatic.net/Iovci.png I am currently facing an issue with my project structure. I received a "Failed to load resource: the server responded with a status of 404 ()" error message, indicating that ShowDetail.jsp is not found. Can anyone advise on ...

By pressing enter, Combobox autocomplete feature automatically selects the first item in the suggestion list

I have successfully implemented a jQuery combobox autocomplete feature, similar to the one on the demo below. jQuery combobox autocomplete Is there a way to configure the jQuery combobox autocomplete to automatically select the top suggestion when the ...

The JavaScript function fails to give back the parameter values

After creating a function in the script tag within the head section that takes two parameters, a and b, to return the product of a multiplied by b, I encountered an issue. When calling the function with the values 3 and 4, nothing was displayed. To troubl ...

Setting the height of columns in a Bootstrap panel to 100%

Is there a way to achieve 100% height for all three columns even without content? Check out this JSFiddle: <div class="row"> <div class="col-md-12"> <div class="shadow panel panel-default"> <div class="blue white-bord ...

having difficulty updating npm to the latest version using windows command prompt

Hey there, I'm currently in the process of updating npm to the latest version. I've been following the instructions from https://www.npmjs.com/package/npm-windows-upgrade to get the newest release. However, I seem to be running into an issue at t ...

Is it better to pass package dependencies into a module function or simply require them within the module file?

When it comes to passing variables to a module, the common practice is exporting modules as a function with parameters for each variable you wish to pass. For example: module.exports = function (injectedVariable) { app.get('/whatever', functio ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

Determine the number of working days prior to a specified date in a business setting

How can I calculate X business days before a given date in JavaScript when I have an array of holidays to consider? I am currently thinking about using a while loop to iterate through the dates and checking if it is a business day by comparing it with the ...

The animation function occasionally halts unexpectedly at a varying position

I am facing an issue with an animation function that I have created to animate a list of images. The function takes in parameters such as frames per second, the stopping point, and the list element containing all the images. However, the animation stops un ...

Enable the execution of a function only once a specific period of time has elapsed

Here's the scenario I'm dealing with: In a fun group chat with my friends, I created a giphy bot that responds to /giphy [terms] messages by posting the top result for those terms. However, my friends started abusing it by spamming the chat. To ...

How to delete a specific element from a scene using three.js

I have an array of Meshes, each Mesh containing its ID in a name property. I'm wondering if it's feasible to remove an object from the scene based on its specific ID. Here is an example: var geo = some geometry; var mat = some material; for (var ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

Empty req.body object in Node.js

I came across this code snippet: const bodyParser = require("body-parser"); const express = require("express"); const app = express(); app.use(express.json()); app.use(bodyParser.json()); app.post("/api/foo", (request, response) => { let foo = { ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...