I'm trying to add an object to my three.js scene for each item in an array. I can't tell if all of the object are adding to the scene because they are adding to the same position, and I can't figure out how to change the position of each object.
Here is the code looping and adding a cube for each item in array:
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
getData()
async function getData() {
const response = await fetch('/api/indexvr');
const data = await response.json();
console.log(data)
for (var i=0; i<data.length; i++) {
try {
scene.add( cube );
// cube.position.y = i //1++
} catch (e) {
console.error(e)
}
}
}
camera.position.z = 5;
I've also tried declaring the cubes and their position in the for loop but that didn't work either. I need for all of the objects to be visible and for their positions to be dynamic depending on the amount in the array, e.g. something like a circle around the camera and if there are more than 10/15, increase the y axis by 4 and continue the circle again.. I can't figure out how or find documentation to help. Any ideas or links to help? Thanks in advance.
EDIT:
the cubes now look like this with the code received from Mugen87.
Try it like so (implements the feedback if @gman):
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
getData()
async function getData() {
const response = await fetch('/api/indexvr');
const data = await response.json();
console.log(data)
for (var i=0; i<data.length; i++) {
var cube = new THREE.Mesh( geometry, material );
cube.position.y = i;
scene.add( cube );
}
}
camera.position.z = 5;