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

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

 メニュー

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

Processing:ニュートンの運動方程式:複数のオブジェクトに作用する力

The Nature of Code(PDF版)からニュートン運動方程式について取り上げます。PVectorを用いて、複数のオブジェクトにニュートン運動方程式を適用させる方法について学びます。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

複数のオブジェクトに作用する力

以下は、複数のオブジェクト(ボール)にニュートン運動方程式を適用させる参考例です。ボールがバウンドします。

  • ボールが受ける力は風と重力
  • 風は左から右に力を加える
  • 重力は上から下に力を加える
  • ボールの質量は0.1~4のランダムな値とする
    • 質量をボールの大きさに反映させている

ちなみに、ボールが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;
    }
  }
}
//Forces acting on many objects
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);

  PVector wind = new PVector(0.01,0);  //風
  PVector gravity = new PVector(0,0.1);  //重力

  for(int i = 0; i < movers.length; i++){
    movers[i].applyForce(wind);
    movers[i].applyForce(gravity);

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

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

プログラムの解説

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

Mover[] movers = new Mover[20];

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

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

void draw() {
  ...
  for(int i = 0; i < movers.length; i++){
    movers[i].applyForce(wind);
    movers[i].applyForce(gravity);

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

まとめ

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

参考サイト

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