Looping through arrays - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

Arrays and loops go hand-in-hand. Arrays have multiple values at sequential indices, and loops allow us to generate sequential numbers, perfect!

The following example uses a loop to generate an array index so that we can assign random locations to all of our targets.

var targetX = new Array(10);
var targetY = new Array(10);

var setup() {
  for (var i = 0; i < targetX.length; i++) {
    targetX[i] = random(width);
    targetY[i] = random(height);
  }
}

Note the use of new Array(10). This creates an array with 10 empty elements in it. Also note the for loop uses targetX.length as the number of times to loop through the array. targetX.length contains the number of elements in the array.

We can also use a loop to draw all of the targets:

var draw() {
  for (var i = 0; i < targetX.length; i++) {
    ellipse(targetX[i],targetY[i], 40, 40);
  }      
}

We will also need to update the collision detection code to detect collisions with all of the targets and reposition any collisions.

for (var i = 0; i < targetX.length; i++) {
  var dx = Math.abs(robotX - targetX[i]);
  var dy = Math.abs(robotY - targetY[i]);

  if (dx < 20 && dy < 20) {
    targetX[i] = random(width);
    targetY[i] = random(height);
    score++;
  }
}

We could use additional arrays to store the size and colour of the targets allowing each target to be more individual.