frameCount % 20 让您走在正确的轨道上。 (或者你也可以use millis())
主要问题是颜色选择是tightly coupled 与矩形绘图。
简而言之,目前只能选择随机颜色和同时渲染,而不能选择颜色和独立渲染(例如在不同时间)
一种选择是使用一个数组来存储每个矩形的颜色,您可以使用两次:
- 将值写入:选择随机颜色
- 从以下位置读取值:渲染矩形时
这是您的草图的修改版本,说明了上述想法:
float size = 20;
color cbw = color(0, 0, 0); //defines BLACK
color cg = color(0, 255, 0); //defines GREEN
color cb = color(0, 0, 255); //defines BLUE
color cw = color(255, 255, 255); //defines WHITE
color[] colors = { //random selects one of above colors
cbw, cg, cb, cw
};
// all colors for each rect
color[][] rectColors;
void setup() {
size(1080, 1080);
// allocate invidual rect colours
rectColors = new color[width/(int)size][height/(int)size];
}
void draw() {
background(255);
if(frameCount%20 == 0){
// randomize colours
int numColors = colors.length;
for (int x = 0; x < width/size; x++) {
for (int y = 0; y < height/size; y++) {
rectColors[x][y] = colors[int(random(0, numColors))];
}
}
}
for (int x = 0; x < width/size; x++) {
for (int y = 0; y < height/size; y++) {
color c1 = rectColors[x][y]; //assigns a random color from above to c1-4
fill(c1);
noStroke();
rect(size*x, size*y, size, size);
}
}
}
就个人而言,我会做一些额外的事情来使其更易于阅读并可能在其他草图中重复使用:
- 将
float size = 20; 更改为int size = 20;,假设您希望网格单元位于整个像素上。这消除了转换的需要(例如宽度/(int)大小)
- 缓存/存储经常重复使用的数据(例如网格行和列)
- 将随机颜色和渲染矩形的循环封装到单独的函数中。甚至像不返回值和不带参数的函数这样简单的东西(例如,很像
void setup())
这可能是这样的:
int size = 20;
color cbw = color(0, 0, 0); //defines BLACK
color cg = color(0, 255, 0); //defines GREEN
color cb = color(0, 0, 255); //defines BLUE
color cw = color(255, 255, 255); //defines WHITE
color[] colors = { //random selects one of above colors
cbw, cg, cb, cw
};
// all colours for each rect
color[][] rectColors;
// grid dimensions
int cols;
int rows;
void setup() {
size(1080, 1080);
// compute grid dimensions
cols = width / size;
rows = height / size;
// allocate invidual rect colours
rectColors = new color[cols][rows];
// call randomize colours function
randomizeColors();
}
// declare randomize colours function
void randomizeColors(){
// read array length, avoding the previosuly hardcoded value (4)
int numColors = colors.length;
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
rectColors[x][y] = colors[int(random(0, numColors))];
}
}
}
void drawRectangles(){
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
color c1 = rectColors[x][y]; //read a random color
fill(c1);
noStroke();
rect(size * x, size * y, size, size);
}
}
}
void draw() {
background(255);
if(frameCount % 20 == 0){
randomizeColors();
}
drawRectangles();
}