What is the best way to animate a sphere rotating around a cube using Three.js?

I've been exploring different options for rotating objects, but I'm not sure how to implement them. As a newcomer to JavaScript, I managed to create a cube and a sphere that rotates around its own axis. However, I need the sphere to rotate around the cube instead. Any guidance would be appreciated.

<html>
    <head>
        <title>Exploring Three.js</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="js/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

            camera.position.z = 25;

            var loader = new THREE.TextureLoader();
            var texture = loader.load('crate.jpg');
            var geometry = new THREE.BoxGeometry( 7, 7, 7 );
            var material = new THREE.MeshBasicMaterial({map: texture});
            var cube = new THREE.Mesh(geometry, material);

            cube.rotation.x += 0.6;
            cube.rotation.y += 0.6;

            scene.add( cube );

            var loader = new THREE.TextureLoader();
            var texture = loader.load('earth.jpg');
            var geometry = new THREE.SphereGeometry( 1, 50, 50 );
            var material = new THREE.MeshBasicMaterial( {map: texture} );
            var sphere = new THREE.Mesh( geometry, material );

            scene.add( sphere );

            var render = function () {
                requestAnimationFrame( render );
                sphere.position.set(6, 0, 15);
                sphere.rotation.y += 0.01;
                renderer.render(scene, camera);
            };

            render();
        </script>
    </body>
</html>

Answer №1

If you're looking for a solution in this scenario, my recommendation would be to utilize an Object3D as a wrapping element for your sphere. Place this container at the center of the cube and apply rotation as needed.

...
var cube = new THREE.Mesh(geometry, material);

cube.rotation.x += 0.6;
cube.rotation.y += 0.6;

scene.add(cube);

...
var sphere = new THREE.Mesh(geometry, material);

sphere.position.set(0, 0, 15); // adjusting position relative to center

var sphereContainer = new THREE.Object3D();
sphereContainer.add(sphere);

sphereContainer.position.copy(cube.position); // optionally assign cube's position if set 

scene.add(sphereContainer);

var render = function () {
    requestAnimationFrame(render);

    sphere.rotation.y += 0.01; // self-rotation
    sphereContainer.rotation.y += 0.01; // rotate around cube

    renderer.render(scene, camera);
};

Answer №2

After some experimenting, I managed to find a solution that actually works. By utilizing the rotateAboutWorldAxis function, I was able to achieve the desired outcome:

...
sphere.position.set(0,0,15); // adjusting for center offset

function rotateAboutWorldAxis(object, axis, angle) {
            var rotationMatrix = new THREE.Matrix4();
            rotationMatrix.makeRotationAxis( axis.normalize(), angle );
            var currentPos = new THREE.Vector4(object.position.x, object.position.y, object.position.z, 1.5);
            var newPos = currentPos.applyMatrix4(rotationMatrix);
            object.position.x = newPos.x;
            object.position.y = newPos.y;
            object.position.z = newPos.z;
            }

In order to make it work properly, I included the following code snippet in the render function:

var yAxis = new THREE.Vector3(0,50,0);
rotateAboutWorldAxis(sphere,yAxis,Math.PI / 180);

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

What is the proper way to trigger a nested jQuery function in HTML?

When calling the addtext() function from onclick() in HTML, nested inside the add() function, how can I go about calling the second function? Here's a link with the add() function that displays a textbox and an ADD button invoking the addtext() funct ...

Which is better: specifying a name in window.open() or using replace?

If the current window is www.myparent.com and a button labeled "a" is clicked, it triggers the following function window.open('children','same','',??). Subsequently, a new page will open as www.myparent.com/children. On the o ...

Concealing a menu once the mouse moves away from both the menu header and the menu content

When hovering over a parent element with a dropdown menu, the menu body appears. The goal is to hide the menu body only when the mouse leaves either the menu head or the menu body itself. So far, the issue is that the body disappears when the mouse leaves ...

What is the process for posting or removing an Instagram like through the Instagram API?

Hey everyone, I'm looking for help on how to post and delete an Instagram like using the API. I've tried to delete a like with the code below, but I'm not receiving any response from the AJAX call. Can anyone point out what I might be doing ...

Client component in Next.js is automatically updated upon successful login

I am currently working on a Next.js + DRF website that requires authentication. I have set up my navbar to display either a "log in" or "log out" button based on a boolean prop passed from the server side to the client-side: export default async function R ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...

I'm having issues with jQuery not functioning properly on my HTML page. The expected alert is not popping up upon page load

For some strange reason, I was expecting the alert "Doc Ready" to pop up, but it's not happening. What could be going wrong? The jQuery library is located in the js directory and I've tested it on all browsers but it's still not working. I a ...

Tips for enabling autofocus in mat-select列表。

I am working on an angular project where I am using Angular Material and a mat-select element. In my form, the mat-select is the first element, and I want to set auto-focus on it when the page loads. However, I have been facing some difficulties achieving ...

Selenium is encountering a validation error when selecting a value from a Drop Down menu

My current project involves automating website testing through selenium. I have encountered a scenario where I need to fill in a mandatory drop-down field. The code snippet I am using to select the drop-down value is as follows: select = Select(find_eleme ...

Using jQuery to Check Cookies and Hide Content Depending on the Value and Data Attributes

On a webpage, I have a collection of coupons with unique data attributes (data-coupon). Currently, I am using cookies to store the value associated with each coupon (ranging from 1 to 4). While my code is functional, it feels repetitive and cumbersome. S ...

Using ReactJS and Ruby on Rails to implement an AJAX delete request

There is a component named Items residing inside a parent component called ItemsContainer. A click on a button within the Items component triggers an Ajax function to delete that specific Item. However, I am encountering a 500 error message at the moment ...

Trigger function upon closing Bootstrap Modal

I am looking for a way to trigger a function whenever my Bootstrap modal is closed, regardless of whether it's done by clicking off the modal, pressing escape, or clicking the "x" close button. Simply using $("#myModal").on("hidden.bs.modal", functi ...

Building a multilingual website using AngularJS UI-Router

I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I ...

Sorting through an array of dates in milliseconds, extracting objects with subcategories, and dynamically displaying them on the calendar based on the specific date

So I am currently working with a JSON object containing an array of objects structured like this: [ { "id": 0, "name": "Sophia Mason", "availability": [ { "date": 1522216800000, "times": ["9:00 am", "2:3 ...

passing data between functions using a shared global variable within an angular controller

Having some difficulty passing a value from one function to another within an Angular controller. I have an event: onTimeRangeSelected: function (args) { $scope.dayPilotCal.clearSelection(); $scope.createNewEventModalWindow(args); ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Leveraging the 'require' method in Node.js for linking with external JavaScript files

Recently, I've been experimenting with using the require function in nodejs to access JavaScript files containing simple scripts. My objective is to require the script and then output its return value to the console. Here's an example of what I c ...

Tips for removing an array within an array: utilizing AJAX to handle JSON data

I'm receiving JSON data from an API with the following output: [[{"first":1}],[{"last":0}],[{"other":4}]] This is my Ajax code: setInterval(function() { $.getJSON('/ytl/public/api/first-hour-trades', function(data) { $.each(data, fu ...

What is the best way to access and compare the values within each <td> element?

, my code looks like this: <table id="table_append"> <tr class='text-center'>" + <td>1</td> <td class="codeverify">025</td> <td> Data1 </td> </tr> ...

Encountered AJAX Issue while trying to access XML document

My goal is to extract information from an XML file using AJAX <?xml version="1.0" encoding=UTF-8"?> <user> <u_idno>1</u_idno> <u_name>nobody</u_name> <u_srnm>nothing</u_srnm> <u_r ...