The Nature of Code(PDF版)からニュートンの運動方程式について取り上げます。今回は、物体の質量を考慮したプログラムについて学びます。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。
重力と質量
以前の記事(PVectorとニュートンの運動方程式:複数のオブジェクトに作用する力)では、質量を1として計算していました。そのため、現実世界で起こる物体の落下現象とは違う動きをしていました。今回は、物体の質量を考慮してプログラミングします。
質量を考慮した落下運動
以下は、物体の質量を考慮したプログラムの参考例です。
class Mover { PVector location; PVector velocity; PVector acceleration; float mass; //質量 //コンストラクタ Mover() { location = new PVector(30,30); velocity = new PVector(0,0); acceleration = new PVector(0,0); mass = 1; } Mover(float m, float x, float y) { location = new PVector(x,y); velocity = new PVector(0,0); acceleration = new PVector(0,0); mass = m; } //力を足し合わせる(力の蓄積) void applyForce(PVector force) { PVector f = PVector.div(force,mass); acceleration.add(f); } //ボールの位置の更新 void update() { velocity.add(acceleration); location.add(velocity); acceleration.mult(0); //力の蓄積をリセットする } //ボールの描画 void display() { stroke(0); strokeWeight(2); fill(0, 127); ellipse(location.x,location.y,mass*16,mass*16); } //ボールがウィンドウから外れたときの処理 void checkEdges() { if (location.x > width) { location.x = width; velocity.x *= -1; } else if (location.x < 0) { velocity.x *= -1; location.x = 0; } if (location.y > height) { velocity.y *= -1; location.y = height; } } }
//Gravity scaled by mass Mover[] movers = new Mover[20]; void setup() { size(400,200); smooth(); for(int i = 0 ; i < movers.length; i++){ movers[i] = new Mover(random(0.1,4),0,0); } } void draw() { background(255); for(int i = 0; i < movers.length; i++){ PVector wind = new PVector(0.01,0); //風 float m = movers[i].mass; PVector gravity = new PVector(0,0.1*m); //重力 movers[i].applyForce(wind); movers[i].applyForce(gravity); movers[i].update(); movers[i].display(); movers[i].checkEdges(); } }
静止画だと分かりにくいので、プログラムを実行して確認することをおすすめします。
プログラムの解説
void setup() { ... for(int i = 0 ; i < movers.length; i++){ movers[i] = new Mover(random(0.1,4),0,0); } }
ボールの生成時に、質量にランダムな値を設定します。ここでは、引数ありのコンストラクタが実行されます。
void draw() { ... for(int i = 0; i < movers.length; i++){ PVector wind = new PVector(0.01,0); //風 float m = movers[i].mass; PVector gravity = new PVector(0,0.1*m); //重力 ... } }
重力の生成時に、重力の力がかかる方向(下向き)にm*g(質量×重力の加速度)を設定します。これでボールの質量が考慮されます。質量の違うボールを同じ高さから落下させると同じタイミングで底に到達します。
まとめ
The Nature of Code(PDF版)からニュートンの運動方程式について取り上げました。今回は、物体の質量を考慮したプログラムについて学びました。引き続き、The Nature of Code(PDF版)の内容を勉強します。