Tutorials

As always this is subject to this license.

OrbitCube

In this tutorial we will have a look at how to make an object orbit around a point using three.js. Go to the demo to see it in action.

Step 1

We are obviously going to need a cube so let's create a cube:

const orbitCube = new THREE.Mesh(
                      new THREE.BoxGeometry(0.8, 0.8, 0.8), 
                      new THREE.MeshPhongMaterial({color:"blue"}));
orbitCube.position.set(0,0,0);
scene.add(orbitCube);

Step 2

To make the cube orbit around a point we have to calculate it's coordinates. If you went to school and had some trigonometry this should be fairly obvious but obviously you didn't or forget about it so that's why you're here.

Cos and Sin

If x is our angle then cos(x) is the x-coordinate and sin(y) is the y-coordinate. cos(x) is defined as the length of the red line and sin(x) is defined as the length of the green line. Thus the point P has the coordinates {cos(x), sin(x)}. Since this is defined on a circle with a radius of 1 we can just multiply these values to increase the distance from the center of the circle. Thus, we can calculate and set our coordinates just like this:

var orbitX = Math.cos(angle);
var orbitY = Math.sin(angle);
    
orbitCube.position.set(orbitX*10, orbitY*10, 0);

The only thing remaining to make it actually orbit is to increase the angle with time. This can be achieved by adding angle += 0.4*delta_t; in your loop where delta_t is the time passed since the last frame in seconds.