Anthony
Anthony

Reputation: 33

Render Multiple Boxes together in THREE.js

I am trying to render multiple boxes together in a structure as in the pic I am providing. I want to test the limitations of GPU as I add more, so then later I will try and optimize. I am using THREE.js, which is written in JavaScript. If possible I would like to implement this task with a three dimensional array. I think this would be the most efficient way. Not sure how to do so in JavaScript though.

[Box group1

Upvotes: 2

Views: 667

Answers (1)

Mugen87
Mugen87

Reputation: 31036

Try it like so:

let renderer, scene, camera;

init();
animate();

function init() {

  // renderer
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(window.devicePixelRatio);
  document.body.appendChild(renderer.domElement);

  // scene
  scene = new THREE.Scene();

  // camera
  camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.set(40, 40, 40);
  camera.lookAt(0, 10, 0);

  // geometry
  const geometry = new THREE.BoxGeometry();
  const edgesGeometry = new THREE.EdgesGeometry(geometry);

  // material
  const material = new THREE.MeshBasicMaterial({
    color: 0xffff00,
  });
  const edgesMaterial = new THREE.LineBasicMaterial({
    color: 0x000000
  });

  // positions
  for (let x = -10; x < 10; x++) {

    for (let y = 0; y < 20; y++) {

      for (let z = -10; z < 10; z++) {

        // mesh
        const mesh = new THREE.Mesh(geometry, material);
        mesh.scale.multiplyScalar(0.9);
        mesh.position.set(x, y, z);
        scene.add(mesh);

        const lines = new THREE.LineSegments(edgesGeometry, edgesMaterial);
        mesh.add(lines);

      }
    }
  }

}

function animate() {

  requestAnimationFrame(animate);

  renderer.render(scene, camera);

}
body {
    margin: 0px;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>

Upvotes: 2

Related Questions