When attempting to rotate a sphere in threejs, the rotation may not function properly if a loop is

I am attempting to rotate a sphere a specified number of times when a button is clicked (with the user selecting the number of rotations). To achieve this, I have implemented a for loop:

$('#clickme').on('click', function () {
    var multiple = 4; //Adjust this value to change rotation angles
    var rotationVector = new THREE.Vector3(0,1,0);
    var angle = ((360 / multiple) * Math.PI) / 180;
    for (var i = 0; i < multiple; i++) {
        sphere.rotateOnAxis(rotationVector, angle);
        alert(i);
    }
});

Currently, the alert serves as a placeholder, but my intention is to perform other actions after each rotation. The issue lies in the fact that the sphere never rotates when inside the loop. While there are no errors and the code executes without problems, the rotation fails to occur. If I remove sphere.rotateOnAxis from the for loop, it functions correctly (rotating once per click). I have attempted various ways to re-render the scene, however, they do not resolve the problem.

For a working example, please visit: http://jsfiddle.net/weatL3nc/2/

Answer №1

Take note of the steps being taken here:

var angle = ((360 / multiple) * Math.PI) / 180;

This calculates an angle by dividing 360 degrees (or 2 π radians) into n slices. Then, in the following block of code:

for (var i = 0; i < multiple; i++) {
    sphere.rotateOnAxis(rotationVector, angle);
}

The object is rotated n times by that calculated angle. This ensures that regardless of the value of multiple, after the loop, a full 360-degree rotation would have occurred. Despite this, it might not be visibly noticeable as upon redrawing the screen, the sphere will appear in its original position.

An alternative approach could involve using setInterval to allow for screen refreshing between frames. An example implementation is demonstrated below:

$('#clickme').on('click', function () {
    var multiple = 2; //Alter this value to vary the rotation
    var rotationVector = new THREE.Vector3(0,1,0);
    var angle = ((360 / multiple) * Math.PI) / 180;
    var frame = 0;
    var ival = setInterval(function() {
        sphere.rotateOnAxis(rotationVector, angle);
        frame++;
        alert('Frame ' + frame + ' of ' + multiple);
        if (multiple == frame)
            clearInterval(ival);
    }, 1);
});

Try it out!

Answer №2

If you want to ensure the render is complete before proceeding, you can utilize a setTimeout() instead of a for loop with a sufficient interval to wait for the render:

var iteration = 0;
var multiple = 4;
var interval = 100; // ms
var angle = ((360 / multiple) * Math.PI) / 180;

function rotateAndSave() {
    iteration++;
    sphere.rotateOnAxis(rotationVector, angle);
    //alert(iteration);
    if (iteration < maxIterations) setTimeout(rotateAndSave, interval);
}

Simply invoke this function when needed:

rotateAndSave();

http://jsfiddle.net/weatL3nc/6/

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

Issues with the JavaScript, HTML, and CSS Counter Implementation

Is there anyone who can assist me in making this code (available at https://jsfiddle.net/hmatrix/v3jncqac/) function properly? Purpose: My goal is to develop a counter that increments by specified values. My HTML: <body onload="incrementCount(10)"> ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...

JavaScript: An object containing a unified handler for all method invocations

Let me explain further. Math.add(2, 2) //4 Math.multiply(4, 9) //36 Whenever a method in the Math object is invoked, it triggers a central processor that interprets the function name to determine its action. Can an object execute a default function when ...

When deploying, an error is occurring where variables and objects are becoming undefined

I've hit a roadblock while deploying my project on Vercel due to an issue with prerendering. It seems like prerendering is causing my variables/objects to be undefined, which I will later receive from users. Attached below is the screenshot of the bui ...

Manipulate the value(s) of a multi-select form field

How can you effectively manage multiple selections in a form field like the one below and manipulate the selected options? <select class="items" multiple="multiple" size="5"> <option value="apple">apple</option> <option va ...

Rendering a Subarray using Map in ReactJS

I have an object containing data structured like this: [{"groupid":"15","items":[ {"id":"42","something":"blah blah blah"}, {"id":"38","something":"blah blah blah"}]}, {"groupid":"7","items": [{"id":"86","something":"blah blah blah"}, {"id":"49","somethin ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...

A step-by-step guide on retrieving a value from a DateTime picker in a React application

I am utilizing Material-UI to create a DateTime picker. You can check out my demo code here. In order to observe the current selected value, I have added console.log to the function handleChange. However, I am facing an issue where the value does not chan ...

Encountered an issue with npm install showing error message 'Failed: connection closed unexpectedly.'

Encountered an issue while running the command npm install module-name --save. The installation fails regardless of the module I try to install. Even specifying it in the package.json and then running npm install for the entire project results in failure ...

Tips for efficiently rendering components in NextJS 13 exclusively on the client side

Currently, I find myself working on a project that demands my components to adjust to constantly changing conditions on the client side. However, it appears that NextJS 13 is leaning towards server-side rendering from what I can gather. I attempted dynamic ...

Create a MongoDB query using AJAX

My goal is to fetch the count of users using the email [email protected] through the ajax request below: function getUserCount(event) { event.preventDefault(); var queryCount = { email:'<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Displaying search results seamlessly on the same page without any need for reloading

I am looking to create a search engine that displays results without the need to refresh the page. I have come across using hash as a potential solution, but I don't have much knowledge about web programming. So far, with the help of tutorials, I have ...

Preserving and Reversing Drag and Drop Canvas Configurations in HTML5 Canvas

With the help of this innovative JS Fiddle, I have successfully created dynamic canvases and enabled the functionality to drag and drop images across multiple canvases. var next = 4 function addCanvas() { // create a new canvas element ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

Modify the background color when hovering using jquery

In order to have buttons with variable colors and a different hover color, I have to apply inline CSS. Since the hover color cannot be added using inline CSS, I need to use JavaScript. I attempted to achieve this using the .hover() function, but the colors ...

Continue to run upon clicking the button in the Document Object Model

I want the code to constantly change instead of executing only once. By default, the button has a dark mode for text and the background color is pink. When you click the button, the background color changes to black and the text in the button turns into li ...

Navigating using Javascript library in Angular 2 framework

I am currently utilizing Parse, an external JS library, within Angular JS 2. Nevertheless, I am encountering issues when attempting to call the function gotoMain() from within a callback function of Parse. It appears that certain elements are not being l ...

Find the line containing the selected text within a JavaScript code

I am working on a contentEditable div where users can enter multi-line text. I need to be able to inspect the line that the user is currently typing in when they press enter. Is there a way to retrieve the context of that specific line (or all lines)? Is ...

Is there a way to pull information from a string and organize it into a two-dimensional array?

Utilizing the axios library, I am pulling data from a website. Unfortunately, the data being fetched is in HTML format. The extracted data looks like this: 1 Agartala VEAT 120830Z 23004KT 5000 HZ SCT018 SCT025 34/27 Q1004 NOSIG= 2 Ahmedabad VAAH 120830Z 23 ...