Search code examples
three.jssquare

square with BoxGeometry OR GridHelper


I'm starting in ThresJS and I want to make a 5 by 5 square with BoxGeometry or via a gridHelper. I want to create this square and be able to fill each box with a different color or not. Here is my code but I think I make an error in because it is in out of memory error

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import Stats from 'three/examples/jsm/libs/stats.module';
import { GUI } from 'dat.gui';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(8, 5, 8);
camera.lookAt(0, 0, 0);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);


var cubes = [];

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({
    color: 0x00ff00,
    wireframe: true
});

for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; i++) {
        let cube = new THREE.Mesh(geometry, material);

        cube.position.x = i;
        cube.position.y = j;

        cubes.push(cube)

        scene.add(cube)
    }
}


window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
}

const stats = Stats();
document.body.appendChild(stats.dom);

const gui = new GUI();
const cubeFolder = gui.addFolder('Cube');

cubeFolder.open();
const cameraFolder = gui.addFolder('Camera');
cameraFolder.add(camera.position, 'z', 0, 10);
cameraFolder.open();

function main() {

    requestAnimationFrame(main);

    render();

    stats.update();
}

function render() {

    renderer.render(scene, camera);
}

main();

Is there something I don't see that would make this mistake.

I thank you in advance

I try make a square 5x5 with ThreeJS and via BoxGeometry, But i have error explain in my previous text. Error : Out of memory


Solution

  • As I can see the problem is in this block of code:

    for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 5; i++) {
            let cube = new THREE.Mesh(geometry, material);
    
            cube.position.x = i;
            cube.position.y = j;
    
            cubes.push(cube)
    
            scene.add(cube)
        }
    }
    

    So, in the inner loop there's incrementing of "i", instead of "j". Just try to change this, worked out in the codesandbox just fine