在这里,我为您制作了一个数组样式示例 :)
int howMany = 100;// 100?
//here you make empty arrays
float[] xv = new float[howMany];
float[] yv = new float[howMany];
float[] xsp = new float[howMany];
float[] ysp = new float[howMany];
void setup() {
size(700, 500);
for (int i = 0; i < xv.length; i++){
//they all have same length so... all at once
// here you populate them...
xv [i] = random(width);
yv [i] = random(height);
xsp[i] = random(-4,4);
ysp[i] = random(-4,4);
}
fill(0,40);
}
void draw() {
background(250);
for (int i =0; i < xv.length; i++){
if(xv[i] > width || xv[i] < 0){
xsp[i] = -xsp[i];
}
if(yv[i] > height || yv[i] < 0){
ysp[i] = -ysp[i];
}
ellipse(xv[i], yv[i], 20, 20);
xv[i] = xv[i] + xsp[i];
yv[i] = yv[i] + ysp[i];
}
}
还有一个类(对象)示例:
int howMany = 100;// 100?
//here you make a empty array of type Sample
//One array to rule them all :)
Sample[] samples = new Sample[howMany];
void setup() {
size(700, 500);
for (int i = 0; i < samples.length; i++) {
// call the constructor to create each sample with random parameters
samples[i] = new Sample(random(width), random(height), random(-4, 4), random(-4, 4));
}
fill(0,40);
}
void draw() {
background(250);
for (int i = 0; i < samples.length; i++) {
//call methods...
samples[i].display();
samples[i].update();
}
}
class Sample {
//class vars
float xv, yv, xsp, ysp;
// a constructor
Sample(float _xv, float _yv, float _xsp, float _ysp) {
xv = _xv;
yv = _yv;
xsp = _xsp;
ysp = _ysp;
}
void update() {
if (xv > width || xv < 0) {
xsp = -xsp;
}
if (yv > height || yv < 0) {
ysp = -ysp;
}
xv+=xsp;
yv+=ysp;
}
void display() {
ellipse(xv, yv, 20, 20);
}
}