I can assign a new value to the variables.
But I can’t use constructor to initialize the variables in the object function.
int nums = 20;
Drop[] drops = new Drop[nums];
void setup() {
size(800, 800);
smooth();
// initialize
for (int i=0; i < drops.length; i++) {
drops[i] = new Drop();
}
}
void draw() {
background(255);
for (int i=0; i < drops.length; i++) {
drops[i].display();
drops[i].move();
//// 1.Works well
//if (drops[i].reachedBottom1()) {
// drops[i] = new Drop();
//}
//// 2.Works well
//drops[i].reachedBottom2();
// 3.Why didn't work?
drops[i].reachedBottom3(drops[i]);
}
}
class Drop {
float x, y;
float speed;
float r;
Drop() {
r = random(2, 6);
x = random(width);
y = -r;
speed = r;
}
void move() {
y += speed;
}
void display() {
fill(50, 100, 150);
noStroke();
circle(x, y, 2*r);
}
// 1.Works well
boolean reachedBottom1() {
if (y > height+r) {
return true;
} else {
return false;
}
}
// 2.Works well
void reachedBottom2() {
Drop drop = new Drop();
if (y > height+r) {
r = random(2, 6);
x = random(width);
y = -r;
speed = r;
}
}
// 3.Why didn't work?
Drop reachedBottom3(Drop self) {
Drop drop = new Drop();
if (y > height+r) {
return drop;
} else {
return self;
}
}
}