回答

問題

クラス-応用5 の回答ページです.

回答例

int n = 100;                              // 円の数
PVector[] location = new PVector[n];      // 位置のベクトルの配列
PVector[] velocity = new PVector[n];      // 速度のベクトルの配列
color[] col = new color[n];               // 塗りの色の配列
float[] diameter = new float[n];          // 円の大きさ(直径)の配列

void setup() {
  size(500, 500);
  noStroke();
  for (int i = 0; i < n; i++) {
    location[i] = new PVector(random(width), random(height));
    velocity[i] = new PVector(random(-5, 5), random(-5, 5));
    col[i] = color(random(256), random(256), random(256), 100);
    diameter[i] = random(3, 40);
  }
}

void draw() {
  background(0);
  for (int i = 0; i < n; i++) {
    fill(col[i]);
    ellipse(location[i].x, location[i].y, diameter[i], diameter[i]);
    location[i].add(velocity[i]);
    if ((location[i].x > width) || (location[i].x < 0)) {
      velocity[i].x *= -1;
    }
    if ((location[i].y > height) || (location[i].y < 0)) {
      velocity[i].y *= -1;
    }
  }
}

解説

配列を5本用意する

PVector[] location = new PVector[n];
PVector[] velocity = new PVector[n];
color[] col = new color[n];
float[] diameter = new float[n];

円1個につき,位置,速度,色,直径の4つの値が必要なので,同じ要素数 n の配列を4本用意します.同じ添字 i の要素をまとめて, i 番目の円の情報として扱います..

色と大きさをランダムに決める

col[i] = color(random(256), random(256), random(256), 100);
diameter[i] = random(3, 40);

color(赤, 緑, 青, 透明度) の4つ目は透明度で,0に近いほど透明,255で不透明です.ここでは100にしているので,円が重なったところは色が混ざって見えます.

直径は random(3, 40) で,3以上40未満の値になります.

fill() は円ごとに実行する

for (int i = 0; i < n; i++) {
  fill(col[i]);
  ellipse(location[i].x, location[i].y, diameter[i], diameter[i]);
  ...
}

fill() で指定した色は,次に fill() を呼ぶまで有効です.このため,円を描く直前に,その円の色 col[i] を毎回指定します.

背景の塗り直し

draw() の最初で background(0) を呼ぶと,前のフレームの円が消えます.軌跡を残さず,円が動いている様子だけが見えます.

端での跳ね返り

if ((location[i].x > width) || (location[i].x < 0)) {
  velocity[i].x *= -1;
}