In my current project, I am creating a Rubik's cube animation using three.js. The main challenge I am facing is implementing a function to shuffle the cube smoothly.
So far, I have successfully developed functions to animate single moves, such as rotating the right face by 90 degrees clockwise. Now, to shuffle the cube, I randomly select 5 moves and execute the corresponding functions one after the other. To achieve this sequential execution, I have decided to utilize promise chaining. However, the animations are currently occurring simultaneously instead of consecutively.
function shuffle(){
let promise = Promise.resolve();
for(let i = 0; i < 5; i++){
promise = promise.then(randomMove);
}
}
function randomMove(){
let side = Math.floor(Math.random()*6);
let turns = Math.floor(Math.random()*3);
MOVES[6*turns+side][1]();
}
function r1(){
let cubiesToRotate = cube.getCubiesByVID([].concat(cube.RIGHT_CENTRAL_CUBIES).concat(cube.RIGHT_CORNER_CUBIES).concat(cube.RIGHT_EDGE_CUBIES));
let group = new THREE.Object3D();
for(let cubie of cubiesToRotate){
group.add(cubie);
}
scene.add(group);
this.rotate(group,new THREE.Vector3(-1,0,0),90*Math.PI/180,0);
}
function rotate(cubies,axis,angle,total){
console.log(axis);
if(total <= angle){
total+=0.05;
cubies.rotateOnAxis(axis,0.05);
renderer.render(scene,camera);
requestAnimationFrame(function(){
cubeAnimator.rotate(cubies,axis,angle,total);
});
}
}
Each function in the code follows a similar pattern:
1. Manipulate the positions of the cubies.
2. Call renderer.render to update the scene.
3. Use requestAnimationFrame to continue the rotation until the desired angle is reached.
While considering a delay between moves using setTimeout is an option, I believe there might be a more elegant solution. I am open to any suggestions or advice on how to achieve a smooth and sequential shuffle animation. Thank you.