回答
Categories:
問題
PVector-応用1 の回答ページです.
回答例
int n = 100; // 円の数
PVector[] positions = new PVector[n]; // 各円の位置
PVector[] velocities = new PVector[n]; // 各円の速度
float[] d = new float[n]; // 各円の直径
void setup() {
size(500, 500);
noStroke();
for (int i = 0; i < n; i++) {
d[i] = random(5, 30);
positions[i] = new PVector(random(d[i] / 2, width - d[i] / 2), random(d[i] / 2, height - d[i] / 2));
velocities[i] = new PVector(random(-5, 5), random(-5, 5));
}
}
void draw() {
fill(0, 15);
rect(0, 0, width, height);
fill(255);
for (int i = 0; i < n; i++) {
positions[i].add(velocities[i]);
ellipse(positions[i].x, positions[i].y, d[i], d[i]);
if (positions[i].x - d[i] / 2 < 0 || positions[i].x + d[i] / 2 > width) {
velocities[i].x *= -1;
}
if (positions[i].y - d[i] / 2 < 0 || positions[i].y + d[i] / 2 > height) {
velocities[i].y *= -1;
}
}
}
解説
PVector の配列を用意する
int n = 100;
PVector[] positions = new PVector[n];
PVector[] velocities = new PVector[n];
float[] d = new float[n];
円の数を変数 n にしておくと,円の数を変えたいときに1か所を書き換えるだけで済みます.
各要素に PVector を作って代入する
for (int i = 0; i < n; i++) {
d[i] = random(5, 30);
positions[i] = new PVector(random(d[i] / 2, width - d[i] / 2), random(d[i] / 2, height - d[i] / 2));
velocities[i] = new PVector(random(-5, 5), random(-5, 5));
}
new PVector[n] で作られるのは「PVector を入れる箱が n 個並んだ配列」が作られます.
100個の円を更新・描画する
for (int i = 0; i < n; i++) {
positions[i].add(velocities[i]);
ellipse(positions[i].x, positions[i].y, d[i], d[i]);
...
}
PVector-基礎1の position を positions[i] に, velocity を velocities[i] に, d を d[i] に置き換えたものです.配列の要素も PVector なので, add() などのメソッドや x , y のフィールドをそのまま使えます.
半透明の四角形は1回だけ描く
半透明の四角形を for 文の中で描くと,
1フレームの中で100回重ねて描くことになり,画面がすぐに暗くなりすぎます.
for 文の前で1回だけ描きます.