How to avoid this type of duplication

That rubics cube is working as good, but the original cube is still intact.
Here is my code, most of the code was being repetitive.

import * as THREE from 'three';
import { scene } from './scripts.js';
import { cubeLayers, edgeLayers } from './cube.js';

function XRotate(layer, angle) {
    layer.rotation.x += angle;
}

const sleep = time => new Promise(resolve => setTimeout(resolve, time));
async function plsRotate(layer, rotateFunction, rev=1) {
    for (var i = 0; i < 25; i++) {
        rotateFunction(layer, rev*Math.PI/2/25);
        await sleep(1);
    }
}

function plsFrontCorrect() {
    plsRotate(frontLayerGroup, XRotate);
}

function plsFrontReverse() {
    plsRotate(frontLayerGroup, XRotate, -1);
}

function plsRearCorrect() {
    plsRotate(rearLayerGroup, XRotate);
}

function plsRearReverse() {
    plsRotate(rearLayerGroup, XRotate, -1);
}

function plsXMiddleCorrect() {
    plsRotate(middleLayerGroupX, XRotate);
}

function plsXMiddleReverse() {
    plsRotate(middleLayerGroupX, XRotate, -1);
}

module.exports = { plsFrontCorrect, plsFrontReverse, plsRearCorrect, plsRearReverse, plsXMiddleCorrect, plsXMiddleReverse };


const frontLayerGroup = new THREE.Group();
for (var i = 0; i < 3; i++) {
    for (var k = 0; k < 3; k++) {
        scene.remove(cubeLayers[i][2][k]);
        scene.remove(edgeLayers[i][2][k]);
        frontLayerGroup.add(cubeLayers[i][2][k].clone());
        frontLayerGroup.add(edgeLayers[i][2][k].clone());
    }
}
scene.add(frontLayerGroup);

const middleLayerGroupX = new THREE.Group();
for (var i = 0; i < 3; i++) {
    for (var k = 0; k < 3; k++) {
        scene.remove(edgeLayers[i][1][k]);
        scene.remove(cubeLayers[i][1][k]);
        middleLayerGroupX.add(cubeLayers[i][1][k].clone());
        middleLayerGroupX.add(edgeLayers[i][1][k].clone());
    }
}
scene.add(middleLayerGroupX);

const rearLayerGroup = new THREE.Group();
for (var i = 0; i < 3; i++) {
    for (var k = 0; k < 3; k++) {
        scene.remove(cubeLayers[i][0][k]);
        scene.remove(edgeLayers[i][0][k]);
        rearLayerGroup.add(cubeLayers[i][0][k].clone());
        rearLayerGroup.add(edgeLayers[i][0][k].clone());
    }
}
scene.add(rearLayerGroup);

when I made a rubiks cube, i made each piece a separate mesh, then using rotationGroup.attach (cubelet) them to a single rotation group object when rotating… then scene.attach(cubelet) them back to the scene when the rotation is done.

https://manthrax.github.io/qube/

2 Likes

Thanks, I’ll try this.

1 Like