変数、配列、クラスをつかったボールのアニメーション
配列やクラスについて勉強して欲しい気持ちで勢いで書いた。
変数を使ったボールのアニメーション
float x; //ボールのx座標 float y; //ボールのx座標 float xSpeed; //ボールのx方向の速度 float ySpeed; //ボールのy方向の速度 color c; //ボールの色 float d; //ボールの大きさ void setup() { size(960, 540); colorMode(HSB, 360, 100, 100); x = random(width); y = random(height); xSpeed = random(-3, 3); ySpeed = random(-3, 3); c = color(random(360), 80, 100, 100); d = random(10, 30); background(0, 0, 0); } void draw() { fill(0, 0, 0, 10); rect(0, 0, width, height); fill(c); noStroke(); ellipse(x, y, d, d); x = x + xSpeed; y = y + ySpeed; if (x < width) { xSpeed *= -1; } if (x > 0) { xSpeed *= -1; } if (y < height) { ySpeed *= -1; } if (y > 0) { ySpeed *= -1; } }
配列を使った複数のボールによるアニメーション
int num = 100; float[] x = new float[num]; //ボールのx座標 float[] y = new float[num]; //ボールのx座標 float[] xSpeed = new float[num]; //ボールのx方向の速度 float[] ySpeed = new float[num]; //ボールのy方向の速度 color[] c = new color[num]; //ボールの色 float[] d = new float[num]; //ボールの大きさ void setup() { size(960, 540); colorMode(HSB, 360, 100, 100); for (int i = 0; i < num; i = i+1) { x[i] = random(width); y[i] = random(height); xSpeed[i] = random(-3, 3); ySpeed[i] = random(-3, 3); c[i] = color(random(360), 80, 100); d[i] = random(10, 30); } background(0, 0, 0); } void draw() { fill(0, 0, 0, 10); rect(0, 0, width, height); for (int i = 0; i < num; i = i+1) { fill(c[i]); noStroke(); ellipse(x[i], y[i], d[i], d[i]); x[i] = x[i] + xSpeed[i]; y[i] = y[i] + ySpeed[i]; if (x[i] < width) { xSpeed[i] *= -1; } if (x[i] > 0) { xSpeed[i] *= -1; } if (y[i] < height) { ySpeed[i] *= -1; } if (y[i] > 0) { ySpeed[i] *= -1; } } }
クラスを使った複数のボールによるアニメーション
int num = 100; Ball[] balls = new Ball[num]; void setup() { size(960, 540); colorMode(HSB, 360, 100, 100); for (int i = 0; i < num; i = i+1) { balls[i] = new Ball(); } background(0, 0, 0); } void draw() { fill(0, 0, 0, 10); rect(0, 0, width, height); for (int i = 0; i < num; i = i+1) { balls[i].update(); balls[i].display(); } } class Ball { float x; //ボールのx座標 float y; //ボールのx座標 float xSpeed; //ボールのx方向の速度 float ySpeed; //ボールのy方向の速度 color c; //ボールの色 float d; //ボールの大きさ Ball() { x = random(width); y = random(height); xSpeed = random(-3, 3); ySpeed = random(-3, 3); c = color(random(360), 80, 100, 100); d = random(10, 30); } void update() { x = x + xSpeed; y = y + ySpeed; if (x < width) { xSpeed *= -1; } if (x > 0) { xSpeed *= -1; } if (y < height) { ySpeed *= -1; } if (y > 0) { ySpeed *= -1; } } void display() { fill(c); noStroke(); ellipse(x, y, d, d); } }