JohnMichael JohnMichael - 10 months ago 84
Javascript Question

2D rotation to 3D with three.js

I'm trying to recreate a functionality of a snippet I found that rotates any given element around another element, very much like a planetary rotation.
I want to use this 2D rotation system for a 3D project with three.js.

The 2D functionality is in this fiddle.

I'm having trouble implementing it in my own scene though. For starters, getting the elements' id's for meshes in three.js is tricky. = "objectName";
var object = scene.getObjectByName( "objectName" );

This example code where you name your meshes and pass it through isn't doing it for me - which marks the only search result I could find.

Also, I don't understand that by adding the third dimension how the trigonometric function would need to be written.

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

So there's some work involved that's simply beyond me. That's why I don't see how the functionality needs to look like for a 3D environment? Thank you if you can help me out with that.

Answer Source

I don't know why you had trouble implementing it because you could almost copy paste from the snippet you found.

I don't know how to use JSFiddle. I clicked update but I have no idea if you can see the changes. That's why I'll post them here as well.

//creates 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);

//creates the 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);
//sets positions
sphere1.position.set(0, 0, 0);
sphere2.position.set(-10, 0, 0);

//adds the two spheres to the scene

//default camera pos
camera.position.z = 400;

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

// 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 

//renders 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 also think you can use this in 3d as well. Because 3d only adds the z-axis and I think that makes no difference. But maybe you can explain me your concerns about using it in 3d.