Processing:万有引力と相互誘引 (original) (raw)

The Nature of Code(PDF版)から万有引力について取り上げます。1つのオブジェクトが別のオブジェクトを引き寄せる相互誘引について学びます。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

相互誘引

以下は、1つのオブジェクトが別のオブジェクトを引き寄せるプログラムの参考例です。

class Mover{ PVector location; PVector velocity; PVector acceleration; float mass;

Mover(float m, float x, float y) { mass = m; location = new PVector(x, y); velocity = new PVector(0, 0); acceleration = new PVector(0, 0); }

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,mass16,mass16); }

PVector attract(Mover m){ PVector force = PVector.sub(location, m.location);
float distance = force.mag();
distance = constrain(distance, 5.0, 25.0);
force.normalize();
float strength = (G * mass * m.mass) / (distance * distance); force.mult(strength);

return force;

} }

Mover[] movers = new Mover[10]; static final float G = 0.4;

void setup() { size(400,200);

for(int i = 0; i < movers.length; i++){ movers[i] = new Mover(random(0.1,2),random(width),random(height)); } }

void draw() { background(255);

for(int i = 0; i < movers.length; i++){ for(int j = 0; j < movers.length; j++){ if(i != j){ PVector force = movers[j].attract(movers[i]);
movers[i].applyForce(force); } } movers[i].update(); movers[i].display(); } }

プログラムを実行して確認することをおすすめします。

プログラムの解説

引力を計算するメソッドをMoverクラスに追加します。

PVector attract(Mover m){ PVector force = PVector.sub(location, m.location);
float distance = force.mag();
distance = constrain(distance, 5.0, 25.0);
force.normalize();
float strength = (G * mass * m.mass) / (distance * distance); force.mult(strength);

return force; }

1つのオブジェクトが別のオブジェクトを引き寄せるのですが、自分自身は除きます。

void draw() { ... for(int i = 0; i < movers.length; i++){ for(int j = 0; j < movers.length; j++){ if(i != j){ PVector force = movers[j].attract(movers[i]);
movers[i].applyForce(force); } } ... } }

まとめ

The Nature of Code(PDF版)から万有引力について取り上げました。1つのオブジェクトが別のオブジェクトを引き寄せる相互誘引について学びました。引き続き、The Nature of Code(PDF版)の内容を勉強します。

参考書籍