I am learning three.js right now and I did build a small function to create a 3x3x3 grid of cubes.
let cubes = [];
function createGrid3x3(gridMaterial, positionZ) {
for( let k = 1; k < 4; k++) {
for( let j = 1; j < 4; j++) {
//3*3 Layer
// j->
// k 0 0 0
// | 0 0 0
// v 0 0 0
cubes[j*k] = new THREE.Mesh(geometry, gridMaterial);
cubes[j*k].position.x = j;
cubes[j*k].position.y = k;
cubes[j*k].position.z = positionZ;
scene.add(cubes[j*k]);
}
}
}
createGrid3x3(material, 1,1);
createGrid3x3(materialTwo, 2,2);
createGrid3x3(materialThree, 3,2);
Now I want to animate each of those cubes.
const clock = new THREE.Clock()
const tick = () =>
{
const elapsedTime = clock.getElapsedTime();
for (var i = 1; i < cubes.length; i++) {
cubes[i].position.y = Math.cos(elapsedTime) * i;
OR
cubes[i].position = Math.cos(elapsedTime) * i;
}
// Render
renderer.render(scene, camera);
// Call tick again on the next frame.
window.requestAnimationFrame(tick);
}
tick();
Depending on if I use
cubes[i].position.y = Math.cos(elapsedTime) * i;
OR
cubes[i].position = Math.cos(elapsedTime) * i;
I get those errors:
Uncaught TypeError: Cannot assign to read-only property 'position' of object '#<Mesh>'
or
Uncaught TypeError: Cannot read properties of undefined (reading 'position')
How can I fix those errors? Why do they appear? I really don't understand why those properties are undefined or read-only if I access them inside an array. If I don't use my function to create those cubes everything works. So I assume it has something to do with the array cubes I created and I don't understand something fundamentally behind it.
I appreciate your help! :)