Lots of Variables
Let's setup up an example to show how powerful and helpful arrays can be. First, we'll do a version without arrays.
PROCESSING
Example 11-1: Many Variables
float x1 = -20; float x2 = 20; int r = 40; void setup() { size(240, 120); noStroke(); } void draw() { background(0); x1 += 0.5; x2 += 0.75; arc(x1, 30, r, r, 0.52, 5.76); arc(x2, 90, r, r, 0.52, 5.76); // Lets add a wrap around if(x1 > width + r) { x1 = -r; } if(x2 > width + r) { x2 = -r; } }
Too Many Variables
Next well do a version that has lots of variables—too many, in fact, and ripe for using an array...
PROCESSING
Example 11-2: Too Many Variables
float x1 = -10; float x2 = 10; float x3 = 35; float x4 = 18; float x5 = 30; int r = 20; void setup() { size(240, 120); noStroke(); } void draw() { background(0); x1 += 0.5; x2 += 0.75; x3 += 1.0; x4 += 1.25; x5 += 1.5; arc(x1, 20, r, r, 0.52, 5.76); arc(x2, 40, r, r, 0.52, 5.76); arc(x3, 60, r, r, 0.52, 5.76); arc(x4, 80, r, r, 0.52, 5.76); arc(x5, 100, r, r, 0.52, 5.76); // Lets add a wrap around if(x1 > width + r) { x1 = -r; } if(x2 > width + r) { x2 = -r; } if(x3 > width + r) { x3 = -r; } if(x4 > width + r) { x4 = -r; } if(x5 > width + r) { x5 = -r; } }
Arrays, Not Variables
Now let's do the same thing, but with an array to hold all those variable values.
PROCESSING
Example 11-3: Arrays, Not Variables
float [] xArray = new float[3000]; // Declare an Array variable with [] int r = 12; void setup() { size(240, 120); noStroke(); fill(255,128); // transparent packmen // pack the array with 3000 random values between -1000 and 200 for (int i = 0; i < xArray.length; i++) { xArray[i] = random(-1000, 200); } } void draw() { background(0); for (int i=0; i < xArray.length; i++) { xArray[i] += 0.05; float yPos = i * 0.04; arc(xArray[i], yPos, r, r, 0.52, 5.76); } }
Playing with Example 11-3
And let's modify the draw loop a bit to get something more visually interesting...
PROCESSING
Example 11-3: Modified
void draw() { background(0); for (int i=0; i < xArray.length; i++) { xArray[i] += 0.05 * (i/10); if (xArray[i] > width * 10) {xArray[i] = 0; } float yPos = i * 0.04; arc(xArray[i], yPos, r, r, 0.52, 5.76); } }