Version 1
here is a version without push / pop
the columns are beneath each other. Bad.
PGraphics img;
void setup() {
size(600, 600);
img = createGraphics(width, height);
img.beginDraw();
img.translate(-10, -10);
for (int x=0; x<10; x++) {
img.translate(10, 0);
img.fill(random(200), random(200), random(200));
for (int y=0; y<10; y++) {
img.translate(0, 10);
img.square(0, 0, 10.0);
}
}
img.endDraw();
//background(0);
image(img, 0, 0);
}
Version 2
in this version, we surround the y for-loop with push / pop (resetting the y after each column)
works well and fixes the error above
no calculation with x and y needed, the translate()
commands add up for x and y
PGraphics img;
void setup() {
size(600, 600);
img = createGraphics(width, height);
img.beginDraw();
img.translate(-10, -10);
for (int x=0; x<10; x++) {
img.translate(10, 0);
img.fill(random(200), random(200), random(200));
img.pushMatrix();
for (int y=0; y<10; y++) {
img.translate(0, 10);
img.square(0, 0, 10.0);
}
img.popMatrix();
}
img.endDraw();
//background(0);
image(img, 0, 0);
}
Version 3
in this version we calculate each cell’s position
push / pop for each cell, only one translate()
command in the Sketch
PGraphics img;
void setup() {
size(600, 600);
img = createGraphics(width, height);
img.beginDraw();
for (int x=0; x<10; x++) {
img.fill(random(200), random(200), random(200));
for (int y=0; y<10; y++) {
img.pushMatrix();
img.translate(x*13+32, y*13+22);
img.square(0, 0, 10.0);
img.popMatrix();
}
}
img.endDraw();
//background(0);
image(img, 0, 0);
}
I don’t think there are severe speed differences between the three versions.
Personally I like version 3 the most, for example because you can make a cell to a class Cell and its display()
method would just work like this. This would be harder in version 2.
Chrisir
[Edited]