A cube matrix

Here’s what an 11×11 matrix of cubes looks like:

Slab of cubes

The function createCubeMatrix(m, n, offset) adds to the scene an m×n matrix of unit cubes where the centers of adjacent cubes are separated by offset units. For each of the m×n positions, a new mesh is constructed and then positioned and added to the scene.

function createCubeMatrix(m, n, offset) {
    let root = new THREE.Object3D();
    offset = offset !== undefined ? offset : 2.0;
    let geom = new THREE.CubeGeometry(1, 1, 1);
    let mat = new THREE.MeshLambertMaterial({transparent: true})
    let xMin = -offset * ((m-1) / 2.0);
    let yMin = -offset * ((n-1) / 2.0);
    for (let i = 0, x = xMin; i < m; i++, x += offset) {
        for (let j = 0, y = yMin; j < n; j++, y += offset) {
            var box = new THREE.Mesh(geom, mat);
            box.position.set(x, y, 0);
            root.add(box);
        }
    }
    return root;
}

This function returns a single node that roots — serves as parent for — all m×n boxes. In another function (not shown), we add this root to the scene:

cubesPerSide = 11;
cubeMatrix = createCubeMatrix(cubesPerSide, cubesPerSide);
scene.add(cubeMatrix);

Here’s what the scene graph looks like:

A cube matrix

Even though the cubeMatrix node has m×n children (in this example, 121 children), all of the same children share the same cube geometry and the same material. This is what makes it easy to change the color and opacity of all the boxes at once: Change these properties of their shared material, and the appearance of every box is affected accordingly.