Animating multiple objects - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

We can store the direction of animation for each individual object.

var targetDX = new Array(5);
var targetDY = new Array(5);

We can initialise the directions randomly in the setup() function:

for (var i = 0; i < targetDX.length; i++) {
  targetDX[i] = random(-5, 5);
  targetDY[i] = random(-5, 5);
}

Note we are passing two parameters to the random() function. This allows us to set a minimum and maximum value. With just one value it is presumed that the minimum value is zero, however we need negative numbers to allow targets to move both left and up.

We now need to animate the targets each frame in the draw() function by adding the direction values to the target locations:

for (var i = 0; i < targetDX.length; i++) {
  targetX[i] += targetDX[i];
  targetY[i] += targetDY[i];
}

The targets ultimately disappear off the edge of the screen so we can add the bounce code from week 3.