Reputation: 11
I have built a Rubik's Cube using Three.js and its all working, but I would like to animate the turning of the cube. Right now, when I turn one side it just snaps into the new position. How can I let it turn slowly?
The code I use right now:
function turnOrangeSide(inverse) {
let x = 0;
let y = 1;
let z = 1;
orangeGroup = new THREE.Object3D();
scene.add(orangeGroup);
//This puts all the parts of the Cube that have to be turned in the group.
orangeGroup.attach(getIntersecting(rotationPointO, x, y, z + 1));
orangeGroup.attach(getIntersecting(rotationPointO, x, y, z - 1));
orangeGroup.attach(getIntersecting(rotationPointO, x, y + 1, z));
orangeGroup.attach(getIntersecting(rotationPointO, x, y - 1, z));
orangeGroup.attach(getIntersecting(rotationPointO, x, y + 1, z + 1));
orangeGroup.attach(getIntersecting(rotationPointO, x, y - 1, z + 1));
orangeGroup.attach(getIntersecting(rotationPointO, x, y + 1, z - 1));
orangeGroup.attach(getIntersecting(rotationPointO, x, y - 1, z - 1));
let rotation = Math.PI / 2
if (inverse) rotation = -Math.PI / 2
orangeGroup.rotation.x += rotation;
}
Live example at https://rekhyt2901.github.io/AlexGames/RubiksCube/RubiksCube.html.
Upvotes: 0
Views: 1462
Reputation: 320
What you could actually do is to use a parametric equation to rotate your cube progressively around an axe.
That would give something like :
let fps = 60; // fps/seconds
let tau = 2; // 2 seconds
const step = 1 / (tau * fps); // step per frame
const finalAngle = Math.PI/2;
const angleStep = finalAngle * step;
let t = 0;
function animateGroup(t){
if (t >= 1) return; // Motion ended
t += step; // Increment time
orangeGroup.rotation.x += angleStep; // Increment rotation
requestAnimationFrame(() => animateGroup(t));
}
animateGroup(t);
Upvotes: 1