Animating a cube with Three.js as it orbits a sphere

I have been working on rotating a cube around a sphere in my project. When I press the spacebar, the cube begins to rotate around the sphere as intended. However, I am facing an issue where the rotation is much faster than expected. I created a function that calculates the rotation using an "angle" parameter. Initially, I thought a full rotation from 0 to 359 degrees would be necessary, but surprisingly, the cube completes a full rotation around the sphere when the angle increases by just 7 degrees.

Here is the relevant code snippet excluding the setup of cube and sphere meshes:


var rotationAngle = 0;
function rotate(angle)
{
    // Rotation logic for cube position around the sphere
}

In the above code, "whiteBall" represents the sphere, and "keu" represents the cube.

Within my render function, I increment the angle and call the rotate function to apply the rotation:


if(isKeyPressed)
{
    if(rotationAngle < 360)
    {
        rotationAngle += 1;
    }
    if(rotationAngle == 360)
        rotationAngle = 0;
}
rotate(rotationAngle);

I am puzzled as to why such a small increase like 7 degrees results in a complete rotation of the cube around the sphere. Any suggestions or code snippets to rectify this behavior would be greatly appreciated.

Answer №1

Consider the x position of the cube as Math.sin(counter) and the y position as Math.cos(counter). The counter variable is incremented within a requestAnimationFrame loop. If the spacebar is pressed, the counter increments; if released, it stops incrementing. To adjust the distance from the center point at which the cube moves, multiply Math.sin(counter) by that distance (in pixels), bearing in mind the sin range (-1 to 1).

A possible code snippet may resemble this:

let isMoving = false;
document.body.addEventListener('keydown', event => {
    if (event.key === 'Space') {
        isMoving = true;
    }
});
document.body.addEventListener('keyup', event => {
    if (event.key === 'Space') {
        isMoving = false;
    }
});

const X = ...; //X coordinate of central point
const Y = ...; //Y coordinate of central point

const distance = 100;
const speed = ...; //speed of cube movement around the sphere
let counter = 0;
let wholeCircle = false; //indicate completion of first revolution
function render() {
    if (isMoving) {
        counter += speed;
    }

    cube.position.x = X + distance * Math.sin(counter);
    cube.position.y = Y + distance * Math.cos(counter);
}

render();

This code is a template for guidance, not to be copied directly. Adjust variables and logic according to your scenario. The use of wholeCircle is omitted but can be implemented based on your requirements.

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

The advantages of utilizing a "for" loop for appending a method to an object Array

Many JavaScript books recommend using a for loop when dealing with an Array of objects to perform a certain action. function() { var links = document.getElementsByTagName("a"); for (var i = 0, ii = links.length; i < ii; i++) { ...

Implementing atomic design principles in Vue 3 with TypeScript

I'm currently implementing atomic design principles in my Vue application. Here is the code for my button atom: <template> <ElButton :type="button?.type" :plain="button?.plain" :rounded="button?.rounded ...

extracting a JSON array from an API

I'm trying to extract the title from my API using JavaScript and then display it in HTML. api:(https://k0wa1un85b.execute-api.us-east-1.amazonaws.com/production/books) The JSON response is as follows: {"statusCode":200,"body":[{"id":"4f160b1f8693cd ...

Can content be dynamically loaded through ajax in Simile Timeline instead of being loaded upfront?

I am currently utilizing the JavaScript Simile Timeline which includes timeline items with extensive description fields. Rather than including all this information in the initial JSON payload data, I only want to load it when a user clicks on a timeline it ...

Struggling to implement touch event functionality for CSS3 spotlight effect

I'm experimenting with implementing touch events on an iPad to achieve a certain effect. Currently, I have it working smoothly with mouse events on JSFiddle at this link: http://jsfiddle.net/FwsV4/1/ However, my attempts to replicate the same effect ...

Utilize JavaScript array to filter, match, and perform calculations based on dates and names

I am working with the following dataset: const data = [ { "employee_name": "Employee A", "commission_date": "14/05/2018", "commission_price": 9000 }, { "employee_name": "Employee A", "commission_date": "17/05/2018", "commissi ...

Steps to set up binance-api-nodeSteps for installing binance

I'm currently attempting to set up binance-api-node on my system. The source repository](https://github.com/Ashlar/binance-api-node) suggests that I can install it using yarn add binance-api-node. However, when I try, I encounter the following error: ...

The dynamic duo: Formik meets Material-UI

Trying to implement Formik with Material-UI text field in the following code: import TextField from '@material-ui/core/TextField'; import { Field, FieldProps, Form, Formik, FormikErrors, FormikProps } from 'formik'; import ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

Experience seamless navigation with Highstock's fluid panning feature

I'm attempting to achieve seamless panning on a basic highstock chart by clicking and dragging within the plot area. Interestingly, I have found that this works flawlessly when my data is not based on timestamps: data: [-25.1,-23.8,-19.9,-19.1,-19.1 ...

Having trouble sending 3 variables through JSON

Having three dropdowns created dynamically by JavaScript, each triggering an 'updateTable' function when a selection is made. The goal is to filter a data table based on choices from the dropdowns. If a user selects just one dropdown option, I w ...

Discovering a specific element within a deeply nested JavaScript object

let data = [{ "ItemAID" : 1, "ItemADesc" : [ { "ItemBid" : 11, "ItemBDesc" : [ { "ItemCid" : 111, "ItemCTitle" : "TitleC111", }, { " ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

Event handlers in JQuery are not connected through breadcrumb links

Wondering how to ensure that the click handler is always attached in my Rails 4.1 app where I am using JQuery-ujs to update cells in a table within the comments#index view. In my comments.js.coffee file, I have the following code snippet: jQuery -> ...

The dropdown selection for redirecting to a URL is malfunctioning within a PHP while loop

<?php $sql = "select * from letter where societyn='" . $_SESSION['socityname'] ."' "; $result = mysql_query($sql); $i=1; while($row=mysql_fetch_array($result)){ ?> <?php $id = $row['id']; ...

Can the console application in a browser be used to search for specific sections of a website based on their color?

Imagine I am browsing a tremendously lengthy webpage that spans over 500 pages. Periodically, certain words are emphasized with a subtle shade of green. Is it possible to search for these highlighted words using the command-line interface in Chrome? ...

Using JavaScript, append a variable to the existing URL

At the moment, I am using this JavaScript code snippet to load a URL based on the dropdown selection... var orderby = jQuery('#dropdown'); var str; orderby.change(function(){ str = jQuery(this).val(); window.lo ...

Executing jQuery AJAX requests in a chain with interdependent tasks

I am struggling to grasp the concept of magic deferred objects with jQuery. Consider the following code snippet: function callWebService(uri, filter, callback) { var data = {}; if (filter && filter != '') data['$filter&apos ...

Adjusting the size of HighCharts HighMaps with a custom function

Simple query here (I believe) I have a DIV with the class "container" acting as my Map. The Highcharts plugin I'm using is responsive, but it only resizes when the window does. I'm looking to manually trigger a resize without adjusting my windo ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...