Recently delving into the world of THREE.js, I've set out on a mission to create a cube composed entirely of cubes, much like this example:
https://i.sstatic.net/hQRoB.jpg
To achieve this, I've structured my 3D array as follows:
[[grid][line,line][[cube,cube],[cube,cube]]]
. Essentially, the cube consists of grids, which consist of lines, and each line is made up of individual cubes. Below is the code snippet:
function lineOfMeshes(w, g) {
var cubes = [];
for (var i = 0; i < w; i++) {
cubes.push(new THREE.Mesh(geometry, material));
cubes[i].position.x += i * g;
}
//console.log("LINE:" + cubes);
return cubes;
}
function gridOfMeshes(w, g) {
cubes = [];
for (var line = 0; line < w; line++) {
cubes.push(lineOfMeshes(w, g));
for (var cube = 0; cube < w; cube++) {
cubes[line][cube].position.z += line * g;
}
}
//console.log("GRID: " + cubes);
return cubes;
}
function cubeOfMeshes(w, g) {
cubes = [];
for (var grid = 0; grid < w; grid++) {
cubes.push(gridOfMeshes(w, g));
for (var line=0;line<w;line++) {
for (var cube = 0; cube < w; cube++) {
cubes[grid][line][cube].position.z += line * g;
}
}
}
//console.log("CUBE"+ cubes);
return cubes;
}
//var container = document.getElementById("3dcontainer");
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
var geometry = new THREE.BoxGeometry(); //object that contains all the points and faces of the cube
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); //material that colors the box
//var cube = new THREE.Mesh(geometry, material); //a mesh is an object that takes a geometry and applies a material to it
///////////////////////////////////////////////////////
let gridWidth = 5;
let gridGap = 3;
cubes = cubeOfMeshes(gridWidth, gridGap);
cubes.forEach(grid => {
grid.forEach(line => {
line.forEach(cube=>{
scene.add(cube);
})
});
});
camera.position.z = 5;
///////////////////////////////////////////////////////
//render loop
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
Unfortunately, upon running the code, I encountered the following error:
index.js:31 Uncaught TypeError: Cannot read property 'position' of undefined
at cubeOfMeshes (index.js:31)
at index.js:65
I'm perplexed by this issue, as I've double-checked my indexing method. Any insights would be greatly appreciated. Thank you in advance.