Not able to change the position of multiple THREE.Mesh Objects in an array "read only" "undefined"

Viewed 27

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! :)

1 Answers

That's because

cubes[i].position = Math.cos(elapsedTime) * i;

is an invalid line. Position is a Vector3 with x, y, z properties, and you're attempting to replace all that information with a basic number, so Three.js isn't letting you. You need to specify what property of position you want to assign a new value. For example, if you want to update the x-value of position:

cubes[i].position.x = Math.cos(elapsedTime) * i;

Related