I am currently exploring the world of three.js and experimenting with some basic concepts. One thing I have been working on is a class that generates cubes in random locations and populates an array with these cubes using a for loop. My goal is to animate all the cubes so they fall slowly at the same time. However, I've run into an issue where only the last cube added to the array seems to animate. Here is the snippet of my code:
class CubeGenerator {
constructor() {
this.cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
this.cubeMaterial = new THREE.MeshLambertMaterial({
color: 0x673612
});
this.cube = new THREE.Mesh(this.cubeGeometry, this.cubeMaterial);
this.cube.position.x = Math.random() * (10 - (-10)) + (-10);
this.cube.position.y = Math.random() * (6 - (-6)) + (-6);
this.cube.position.z = Math.random() * (6 - (-6)) + (-6);
scene.add(this.cube);
}
}
var cubeArray = [];
for(var i = 0; i < 22; i++) {
var newCube = new CubeGenerator();
cubeArray.push(newCube);
};
var fallSpeed = 0.01;
var animateCubes = function() {
requestAnimationFrame(animateCubes);
cubeArray.forEach(function(cube) {
cube.cube.position.y -= fallSpeed;
});
renderer.render(scene, camera);
};
animateCubes();
Any assistance or guidance would be highly appreciated! Thank you.