animationthree.jstweensplinerequestanimationframe

Move object along spline(circle) in Three.js


I'm pretty new to Three.js (1 day experience lol) I want to create a model of Solar system so I got planets that should move along their trajectories (circles).

function render() { 
    requestAnimationFrame(render); 

    sun.rotation.y += 0.01;
    mercury.rotation.y +=0.03;

    renderer.render(scene, camera); 
} 
render();

I tried to use splines for this, but failed to animate because I don't get how to use requestAnimationFrame with variables (only this simplest incremental stuff like +=0.03)

mercury.position = spline.getPoint(t);

Also tried to do it with math, but same result. Don't know how to animate variables.

mercury.position.x = 20*Math.cos(4) + 0;

But I don't have any experience in animating anything in JS. So my mind is blown away by this requestAnimationFrame thing, that I got from some tutorial, it's like a black box to me.


Solution

  • Found a solution:

    const sunGeo = new THREE.SphereGeometry(12, 35, 35);
    const sunMat = new THREE.MeshPhongMaterial();
    sunMat.map = THREE.ImageUtils.loadTexture("image/sunmap.jpg");
    const sun = new THREE.Mesh(sunGeo, sunMat);
    sun.position.set(0, 0, 0);
    scene.add(sun); // add Sun
    
    const mercuryGeo = new THREE.SphereGeometry(2, 15, 15);
    const mercuryMat = new THREE.MeshPhongMaterial();
    mercuryMat.map = THREE.ImageUtils.loadTexture("image/mercurymap.jpg");
    const mercury = new THREE.Mesh(mercuryGeo, mercuryMat);
    scene.add(mercury); // add Mercury
    
    let t = 0;
    function render() {
        requestAnimationFrame(render);
        t += 0.01;
        sun.rotation.y += 0.005;
        mercury.rotation.y += 0.03;
    
        mercury.position.x = 20 * Math.cos(t) + 0;
        mercury.position.z = 20 * Math.sin(t) + 0; // These to strings make it work
    
        renderer.render(scene, camera);
    }
    render();