元Webデザイナー兼コーダーの備忘録

ウェブデザインやプログラミング、ブログのカスタマイズなどについてアウトプットしています。

 メニュー

» HTML入門のまとめはこちらです。

Processing:万有引力と複数のオブジェクトに作用する力

The Nature of Code(PDF版)から万有引力について取り上げます。PVectorを用いて、複数のオブジェクトに万有引力を適用させる方法について学びます。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(1, 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,mass*16,mass*16);
  }
}
class Attractor{
  float mass;
  float G;  //引力の定数
  PVector location;

  //コンストラクタ
  Attractor(){
    location = new PVector(width/2, height/2);
    mass = 20;
    G = 0.4;
    //dragOffset = new PVector(0.0, 0.0);
  }

  //引力を計算して返す
  PVector attract(Mover m){
    PVector force = PVector.sub(location, m.location);  //2点間のベクトル
    float distance = force.mag();  //2点間の距離
    distance = constrain(distance, 5.0, 25.0);  //距離の制限
    force.normalize();  //力の方向の取得
    float strength = (G * mass * m.mass) / (distance * distance);
    force.mult(strength);

    return force;
  }

  //アトラクタの描画
  void display(){
    stroke(0);
    fill(175, 200);
    ellipse(location.x, location.y, mass*2, mass*2);
  }
}
//Attraction with many Movers
Mover[] movers = new Mover[10];
Attractor attractor;

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));
  }
  attractor = new Attractor();
}

void draw() {
  background(255);

  attractor.display();

  for(int i = 0; i < movers.length; i++){
    PVector force = attractor.attract(movers[i]);  //引力
    movers[i].applyForce(force);

    movers[i].update();
    movers[i].display();
  }
}

静止画だと分かりにくいので、プログラムを実行して確認することをおすすめします。

プログラムの解説

Mover型の配列を用意して、ボールを複数個生成します。初期化時に質量とx座標、y座標にランダムな値を設定しています。

Mover[] movers = new Mover[10];

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

draw()メソッド内で、複数のボールに処理を実行します。

void draw() {
  ...
  for(int i = 0; i < movers.length; i++){
    PVector force = attractor.attract(movers[i]);  //引力
    movers[i].applyForce(force);

    movers[i].update();
    movers[i].display();
  }
}

まとめ

The Nature of Code(PDF版)から万有引力について取り上げました。PVectorを用いて、複数のオブジェクトに万有引力を適用させる方法について学びました。引き続き、The Nature of Code(PDF版)の内容を勉強します。

参考サイト

» HTML入門のまとめはこちらです。