We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi All,
I am currently fiddling with an array of rectangles and was wondering how I could get the rectangles to display a random color only once. Now they are constantly changing due to the fact that they are placed in draw. Code is below.
Thanks! M
int ammount= 100;
Rectangle[] rectangles = new Rectangle[ammount];
void setup(){
size(400,800);
for (int i = 0; i < ammount; i++){
rectangles[i] = new Rectangle();
}
}
void draw() {
background(163, 163, 163);
for (int i = 0; i < rectangles.length; i++) {
rectangles[i].display();
}
}
and the class:
class Rectangle {
float x,y,widthrect,heightrect;
Rectangle() {
x = random(width);
y = random(height);
widthrect = random(5,100);
heightrect = random(5,100);
}
void display() {
stroke(0, 0, 0);
rect(x, y, widthrect, heightrect);
fill(random(255),random(255),random(255));
}
}
Answers
Instead of filling each Rectangle with a random color (which should happen before you draw the Rectangle's rectangle! Swap lines 14 and 15 in that class!), you should instead set the fill color to the color of the Rectangle. This means that you will need to add a new variable to the class that records a Rectangle's color. You already have variables for each Rectangle that record its position and size, so use those as an example of how to do so. Define the new color variable in the class but outside of any of the class's functions. Set the initial value for this color variable (to a random color!) in the class's constructor function, and use that color variable for the fill color when you are drawing the rectangle. Notice this value will not change since the constructor function for each Rectangle is only called once, from
setup()
.Thanks! resolved