In this exercise we will created a three-dimensional grid of objects using nested loops.


Before we start this exercise, it is best to go through our GRID 1D and GRID 2D exercises if you have not done so already.

Before we start coding, we should first think about the desired outcome and what variables would be needed to achieve this. We are creating a three dimensional grid of objects and this therefore means we will be working with the x, y and z axis. Now that we know what we want, lets think of the parameters we would need to consider to build this.

Essentially, we would need to set up how any rows of objects we want on the x, y & z axes, we would also need to set up the sizes for each dimension and we would also need to calculate the size of the gap between the objects along along all three axes.

this.dimX = 20;
this.dimZ = 20;
this.dimY = 10;

this.countX = 4;
this.countZ = 4;
this.countY = 4;

this.segDimX = this.dimX/(this.countX-1);
this.segDimZ = this.dimZ/(this.countZ-1);
this.segDimY = this.dimY/(this.countY-1);

Now that we have our variables, we need to create an iteration where we nest our GRID 2D loop in a loop that iterates “this.countZ” times and calculates the z position.

for(let iZ=0; iZ<this.countZ; iZ++){

   let z = iZ* this.segDimZ - this.dimZ/2;
   for(let iY=0; iY<this.countY; iY++){

      let y = iY* this.segDimY - this.dimY/2;

      for(let iX=0; iX<this.countX;iX++){

         let x = iX* this.segDimX - this.dimX/2;
         let objMesh = new THREE.Mesh(geometry, material);
         objMesh.position.set(x, y, z);


See the Pen GRID 3D by XR Club (@xrclub) on CodePen.

Leave a Reply

Your email address will not be published.