I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to read data[0] which is 49, and the second material object [cubeMaterialTwo] to read data[1] which is 7.
Check out my code snippet below:
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d6cad0c7c7e2928c93939a8c91">[email protected]</a>/build/three.js"></script>
let scene, camera, renderer;
let cubeGroup;
init();
animate();
function init() {
const data = [
[49, 7]
]
var i = 1;
width = 500
height = 500
fov = 9
aspect = 1/5
near = .1
far = 1000
loader = new THREE.TextureLoader()
scene = new THREE.Scene(); // ADDED
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(50, 30, 50);
camera.lookAt( scene.position );
cubeGeometries = data.map(row => {
return row.map(c => {
return new THREE.BoxBufferGeometry(0.2, c / 8, 0.2);
})
})
var materialArray = [];
const cubeMaterial = new THREE.MeshBasicMaterial({
map: loader.load('../path/to/.jpgOne')
});
cubeMaterial.color.convertSRGBToLinear();
const cubeMaterialTwo = new THREE.MeshBasicMaterial({
map: loader.load('../path/to/.jpgTwo')
});
cubeMaterialTwo.color.convertSRGBToLinear();
materialArray.push(cubeMaterial, cubeMaterialTwo);
const cubeMeshes = cubeGeometries.map(row => {
return row.map(cubeGeometry => new THREE.Mesh(cubeGeometry, materialArray))
})
cubeGroup = new THREE.Group();
data.forEach((row, i, iarr) => {
row.forEach((d, j, jarr) => {
cubeMeshes[i][j].position.set(
i / iarr.length - 0.5,
d / 8 * 0.5 - 0.6,
j / jarr.length - 0.5);
//cubeMeshes[i][j].scale.set(1,4,1);
cubeGroup.add(cubeMeshes[i][j]);
})
})
const mainLight = new THREE.DirectionalLight(0xffffff, 5.0);
mainLight.position.set(10, 10, 10);
const ambientLight = new THREE.HemisphereLight(0xddeeff, 0x202020, 3);
var material = new THREE.LineBasicMaterial({
color: 0x0000ff
});
scene.add(cubeGroup);
scene.add(mainLight);
scene.add(ambientLight);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.physicallyCorrectLights = true;
document.body.appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame( animate );
cubeGroup.rotation.y += 0.005;
renderer.render( scene, camera );
}