We construct a box that rotates on its own axis every 2 seconds while revolving around the z-axis every 10 seconds. (Revolution is simply rotation around some axis outside an object. So we say the earth rotates on its axis while revolving around the sun.)
We build a two-level scene graph. The parent node boxRoot
rotates around the z-axis to effect the revolution. Its child node box
then translates and rotates locally in the revolved space. The following function prepares the scene graph whereas the update
function performs the rotations incrementally over time.
function makeRotatingRevolvingBox() { let geom = new THREE.CubeGeometry(4, 1, 1); let mat = new THREE.MeshLambertMaterial({color: 'blue'}); let box = new THREE.Mesh(geom, mat); box.position.x = 4; box.rps = 0.5; // rotation every 2 seconds let boxRoot = new THREE.Object3D(); boxRoot.rps = 0.1; // revolution every 10 seconds boxRoot.add(box); return boxRoot; }
The property boxRoot.rps
stores the rate of revolution whereas the property box.rps
stores the rate of rotation. These are used by the update
function to change the angles of revolution and rotation on every frame refresh.
function update() { let delta = clock.getDelta(); let deltaRevRadians = rpsToRadians(boxRoot.rps, delta); boxRoot.rotation.z += deltaRevRadians; boxRoot.rotation.z %= 2 * Math.PI; let box = boxRoot.children[0]; let deltaRotRadians = rpsToRadians(box.rps, delta); box.rotation.z += deltaRotRadians; box.rotation.z %= 2 * Math.PI; }