In this exercise we will created a two-dimensional grid of objects using nested loop.


Before we start this exercise, it is best to go through our GRID 1D exercise 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 two dimensional grid of objects and this therefore means we will be working with the x and y 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 axis as well as the y axis, we would also need to set up the width and length (the size of dimension X and Y respectively) and we would also need to calculate the size of the gap between the objects along the x axis and also the y axis.

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

this.countX = 5;
this.countY = 8;
this.segDimX = this.dimX/(this.countX-1);
this.segDimY = this.dimY/(this.countY-1);

Now that we have our variables, we need to create an iteration where as we go “this.countY” times on the y axis, we place “this.countX” objects on the x axis. In this case we would need a nested loop.

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 obj = new THREE.Mesh(geometry, material);
      obj.position.set(x, y, 0);
      this.scene.add( obj );

A nested loop is a loop that is present inside another loop. In our exercise, we have the main loop that iterates “this.countY” times and in this loop the y position is calculated and we run the inside loop. The loop inside runs “this.countX” times, it calculates the x position, it creates an object, it sets the object x & y position and adds it to the scene.

See the Pen Grid 2D by XR Club (@xrclub) on CodePen.

Leave a Reply

Your email address will not be published.