Step 11. Make lots of boxes

To see the power of programming, we will make lots of boxes, using what is called a "for" loop.

Insert the following code at the top:

// make an array of random (x,y,z) positions 

const noboxes = 30;                 	// how many boxes to have 
var a = new Array(noboxes);         	// array of the box positions

for ( var i=0; i < noboxes; i++ )   	// set up the array
{
    a[i] = [ AB.randomIntAtoB(-500,500), AB.randomIntAtoB(-500,500), AB.randomIntAtoB(-500,500) ];
}	

Insert the following code inside "draw", replacing the previous "box" and "translate" instructions:

for ( var i=0; i < noboxes; i++ )
{
  translate ( a[i][0], a[i][1], a[i][2] );		// get box position i 
  box(objectsize);             
}

Don't worry about understanding this code. If you want to read further, it uses a for loop and an array. But we do not need to understand it to paste it in. We just want to demo the power of programming so you get an idea where this is heading.

Your World will now make a large number of boxes in randomly different places, like the following image. Increase the number of boxes until your browser cannot cope. Don't worry, you cannot cause any damage!



More on "translate": The P5 translate function is in fact cumulative or relative positioning, rather than absolute positioning. To do absolute positioning, see: P5 translate versus absolute position.

Tweet this step: