Once you understand how the for loop and arrays work the world is your oyster.
For loop
void setup(){
size (400, 400);
}
void draw(){
for (int i=0; i< width; i += 5) { // i starts at 0, while it is less than 400 do the following, add 5 to i each iteration.
stroke(20, 200, 60);
strokeWeight(1);
line(i, 0, i, height); // draw horizontal lines
line(0, i, width, i); // draw verticle lines
} // closes the for loop.
}
A for statement inside a for statement. So for each instance of "i" it runs through the entire "j" loop.
void setup(){
size (400, 400);
}
void draw(){
for (int i=0; i< width; i += 15) {
for (int j=0; j< width; j += 15) { // i starts at 0, while it is less than 400 do the following, add 5 to i each iteration.
strokeWeight(1);
ellipse (i, j, 8, 8);
}
}
}
Arrays are lists of variables. The list can be of int, float, string, pictures - anything that can be a variable. The only stipulation is that the array has to be all of the same thing.
int arraysize = 3; // how may places will be in our array
int Xlocation [] = new int[arraysize]; // delare an array and establish an array size
void setup(){
size (400, 400);
Xlocation [0] = 30; // notice the first position of an array is 0 not 1!
Xlocation [1] = 100;
Xlocation [2] = 200; // notice the LAST position of this array is 2 not 3! AAAARG!
println (Xlocation);
}
void draw(){
ellipse (Xlocation[0], 50, 30, 30); // gets the first location of the array.
ellipse (Xlocation[1], 70, 30, 30);
ellipse (Xlocation[2], 200, 30, 30);
}
here's another way to declare an array, and a for loop to access the array
int Xlocation [] = { 30, 100, 200 }; // delare an array and establish an array size
void setup(){
size (400, 400);
}
void draw(){
for (int i=0; i< 3; i++){
ellipse (Xlocation[i], 50, 30, 30); // gets the first location of the array.
}
}
If we tried to do this without an array we'd need to have 60 variables!
float speed = 2;
int arraysize = 30; // how may places will be in our array
float Xlocation [] = new float[arraysize]; // delare an array and establish an array size
float Ylocation [] = new float[arraysize]; // delare an array and establish an array size
void setup(){
size (400, 400);
for (int i=0; i < arraysize; i++){
Xlocation[i] = random(width);
}
for (int i=0; i < arraysize; i++){
Ylocation[i] = random(height);
}
}
void draw(){
background(100);
smooth();
for (int i=0; i< arraysize; i++){
Xlocation[i] += speed;
if (Xlocation[i] > width) {
Xlocation[i] = 0;
}
ellipse (Xlocation[i], Ylocation[i], 30, 30); // gets the first location of the array.
}
}
Take the code above and make each ball move at a different speed