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

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

 メニュー

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

Processing:万有引力と相互誘引

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,mass*16,mass*16);
  }

  //引力を計算して返す
  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;
  }
}
//Mutual attraction
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);  //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;
}

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版)の内容を勉強します。

参考書籍

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