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

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

 メニュー

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

Processing:ニュートンの運動方程式

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

ニュートン運動方程式

F=ma

  • F(force):力
  • m(mass):質量
  • a(acceleration):加速度

この式を以下のように変形します。

a=F/m

この式をプログラムで使用します。この式から次のようなことが言えます。加速度は力に比例し、質量に反比例します。

ニュートン運動方程式を適用する例

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

  • ボールが受ける力は風と重力
  • 風は左から右に力を加える
  • 重力は上から下に力を加える
  • ボールの質量は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;
  }

  //力を足し合わせる(力の蓄積)
  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(127);
    ellipse(location.x,location.y,mass*48,mass*48);
  }

  //ボールがウィンドウから外れたときの処理
  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 and Newton’s Laws of Motion
Mover m;

void setup() {
  size(400,200);
  smooth();
  m = new Mover();
}

void draw() {
  background(255);

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

  m.update();
  m.display();
  m.checkEdges();
}

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

プログラムの解説

ボールに風と重力の力を適用させる記述は以下です。

void draw() {
  ...
  PVector wind = new PVector(0.01,0);  //風
  PVector gravity = new PVector(0,0.1);  //重力
  m.applyForce(wind);
  m.applyForce(gravity);
  ...
}

applyForce()メソッドでは、2つのことをしています。

  1. a=F/mより、与えられた力から加速度(f)を求める
  2. それをボールの加速度に足す
//力を足し合わせる(力の蓄積)
void applyForce(PVector force) {
  PVector f = PVector.div(force,mass);
  acceleration.add(f);
}

このプログラムでは、2つの力(風と重力)の加速度をボールの加速度に足します。

update()メソッドに、加速度をリセットする処理を追記します。

//ボールの位置の更新
void update() {
  ...
  acceleration.mult(0);  //力の蓄積をリセットする
}

まとめ

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

参考サイト

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