Transforming 2D rotation into 3D using three.js

I stumbled upon a fascinating snippet that allows elements to rotate around another element, mimicking planetary rotation. I'm eager to incorporate this 2D rotation feature into a three.js project for a more immersive 3D experience.

The demo showcasing the 2D functionality can be found in this example.

However, I'm encountering difficulties while trying to integrate it into my own scene. Identifying the IDs of meshes in three.js poses a challenge initially.

myObject.name = "objectName";
...
var object = scene.getObjectByName( "objectName" );

The suggested method of naming and retrieving meshes didn't work out as expected - unfortunately, it was the only reliable solution I could locate.

Furthermore, I am struggling to comprehend how to adjust trigonometric functions when transitioning from 2D to 3D.

return {
        x: Math.cos(ang) * r - Math.sin(ang) * r + coorX, 
        y: Math.sin(ang) * r + Math.cos(ang) * r + coorY 
    };

It seems there are complexities beyond my current skill level. If anyone could shed light on how this functionality should look like in a 3D environment, I would greatly appreciate your assistance.

Answer №1

It's interesting that you encountered difficulties implementing this, as you could simply copy and paste from the snippet you discovered.

I'm not familiar with JSFiddle either. I clicked update, but I'm uncertain if you can view the changes. That's why I'll include them here too.

//Setting up the scene
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 500 / 400, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setClearColorHex(0xffffff, 1);
renderer.setSize(625, 500);
document.body.appendChild(renderer.domElement);

//Creating two objects
var geometry = new THREE.SphereGeometry(1.5, 50, 50);
var material = new THREE.MeshPhongMaterial({ color: 0x9a806e });
var sphere1 = new THREE.Mesh(geometry, material);
var sphere2 = new THREE.Mesh(geometry, material);
//Setting positions
sphere1.position.set(0, 0, 0);
sphere2.position.set(-10, 0, 0);

//Adding spheres to the scene
scene.add(sphere1);
scene.add(sphere2);

//Default camera position
camera.position.z = 400;

var object = { speed: 1.2, spin: 100, side: 0.0 };

//Function for rotation (copied from snippet)
function rotation(coorX, coorY, object) {
    object.side += (1.0 / object.speed);
    var ang = object.side * 2.0 * Math.PI / 180.0;
    var r = object.spin;

    return {
        x: Math.cos(ang) * r - Math.sin(ang) * r + coorX,
        y: Math.sin(ang) * r + Math.cos(ang) * r + coorY
    };
}

//Rendering the scene
var render = function () {
    newpos = rotation(sphere1.position.x, sphere1.position.y, object);
    sphere2.position.x = newpos.x;
    sphere2.position.y = newpos.y;
    renderer.render(scene, camera);
};

setInterval(render, 1000 / 60)

I believe this can also be utilized in 3D, as adding the z-axis only introduces depth. Feel free to elaborate on any concerns you may have regarding its usage in 3D.

Answer №2

Check out this innovative method that leverages three.js to handle trigonometry effortlessly: http://jsfiddle.net/SF9tX/438/

Key code snippet:

var sphere2Rig = new THREE.Object3D();

sphere2.position.x = -10;
sphere2Rig.add(sphere2);
scene.add(sphere2Rig);

var render = function () {
    sphere2Rig.rotation.z -= 0.025;
    renderer.render(scene, camera);

    requestAnimationFrame(render);
};

By creating a "rig" positioned at the origin and containing the sphere2-object placed elsewhere, you can easily rotate all children simultaneously by rotating the rig itself. The rig's origin serves as the central rotation point for all child elements.

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

Delay the HTTPs request until the password encryption is complete

Hey there! I'm working on a post request where I need to collect login data (name, email, password) from users, validate it, encrypt the password, and then store the data. However, I'm facing an issue with the encryption function taking time to r ...

Stanza.io encountered difficulties in generating a WebRTC answer

I have successfully set up a realtime messaging website using ejabberd + stanza.io. Everything works perfectly, and now I want to integrate Webrtc audio/video using the jingle protocol. Below is the JS code I am using for connection: var client = XMPP.cre ...

Ensure that the folder name contains specific characters

When working with AngularJS, I am developing a feature to create folders. One requirement is that if a folder name contains special characters like /, :, ?, "<", or |, an error message should be displayed stating "A folder name cannot contain any of the ...

A guide on efficiently traversing a disk directory, recursively fetching all paths in relative format, and converting them into a JSON stream with node.js

My goal is to traverse a directory tree and store it in a JSON file using node.js with the following approach: Open specified directory Convert paths into a relative format. For example: Directory: C:/test { {"C:/test folder 1": [ {"folder 1": ["fil ...

When Electron's WebView.loadURL is called, it initiates a reloaded page

According to the documentation provided by Electron, it is necessary to wait until the webview element is available in order to utilize its respective methods. While most methods function properly, I am facing challenges in understanding how to programmati ...

Optimizing performance: Enhance readback operations in Canvas2D by enabling the willReadFrequently attribute for faster getImageData processing

I am currently utilizing the react-wordcloud package and encountering an issue where the word cloud adjusts to fit 70% of the screen size whenever the container size changes. My console is being flooded with this warning message: https://i.sstatic.net/vdV ...

Having trouble with the placeholder blur feature on images in Next.js?

Within my website, I have a dynamic route set up as /titles/[slug].js. Upon initially navigating to this route, everything functions as expected - the placeholder blur effect displays on all images and animations triggered by react-intersection-observer wo ...

The radio button fails to trigger the setState function in React

In my React program, I have implemented a method to update the state and modify a specific value for a Radio button: The state : class App extends Component { constructor(props) { super(props); this.state = { checked: [], expanded: [], ...

The latest alpha version of Angular2 Material Design (alpha.9-3) encountered a "404 not found" error when trying to access @angular

After carefully following the steps outlined in the angular material2 Getting Started guide to install @angular/material, I made updates to package.json, app.module, and systemjs.config using Atom. Specifically, I added the line '@angular/material&apo ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

Discover the best approach for transforming a complicated JSON object/array into a map using inheritance coding techniques

Could someone help me with creating an array of objects (only 1 level) based on the following JSON structure? [ { 'family' : { 'name' : 'Doe', 'from' : 'Foo' }, ...

Incorporating an HTML Canvas element within a CSS grid design

I've been attempting to integrate an html canvas that I created into one of the css grid classes specified in my code. The code runs when the "Calculate" button is clicked. Upon clicking the button, the <div> section designated for the canvas r ...

Clicking on the Material-UI slider that uses multiple useState causes duplication issues

Seeking help to develop a font size and font weight previewer utilizing Material-Ui sliders and useState. Encountering an issue where clicking the first slider after the second results in duplicating the first slider. https://i.sstatic.net/5MAzgtHO.png B ...

Efficiently add an object to the beginning of an array in React/Redux by utilizing the spread

I've been trying to use a redux reducer to add objects to a state array. Everything seems to be working fine, except for one issue. The objects are always added to the end of the array, when I really need them to be placed at the beginning. I've ...

Restricting movement in Jquery draggable through the drag function

I am facing a challenge with using jQuery draggable within a complex geometrical shape that cannot be pre-determined. Due to this complexity, the containment option is not suitable for solving this issue. I have considered using the drag function to chec ...

Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of ...

Adding elements to a list using the appendChild method

Hey there! I have a bunch of images and I'm trying to create a navigation list item for each image. Here's the code I currently have: var bigImages = $('#imagesList li img'); // grabs the Big Images Next, I've set up a ul with t ...

What is the technique for utilizing JavaScript to toggle the opening and closing of a Bootstrap 5 navbar dropdown?

My website is built using Bootstrap 5, and I am working on creating a navbar dropdown functionality. On desktop, I want the dropdown to open on hover and lead to a new page when clicked. However, on mobile, I only want the dropdown to open and close on cli ...

How can user input be converted into a JavaScript variable?

Looking for help with my webpage - I want users to input their name and age. After hitting submit, I'd like the first input to be stored in a variable called 'name', and the second input in a variable called 'age'. Is this doable? ...

Unable to transmit an object containing a property that includes an array of other objects

I am attempting to send an object that has the following structure: var postBody = { id: userID, objectID: [0, 1], objects: [ {id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0. ...