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

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

 メニュー

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

Proccesing:三角法と力:振り子

「The Nature of Code」から振り子について取り上げます。振り子にかかる力を計算して、振り子をシミュレーションします。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

振り子の構成

振り子を分解して考えます。

  • 振り子の起点の座標
  • 振り子の腕
    • 腕の長さ
    • 腕の角度
    • 球の半径
    • 角速度
    • 角加速度

振り子の描き方

角速度、加速度を使って振り子を描きます。振り子を描くには、以下の計算をします。

  1. 振り子にかかる力を計算する
  2. 振り子の角加速度 = 重力加速度 * sin(θ)
  3. (x, y)の位置に応じて、振り子の腕と球を描く
  4. 角速度に応じて角度を増やす

振り子のシミュレーション

以下は、振り子の参考例です。

//Swinging pendulum
Pendulum p;
 
void setup() {
  size(200,200);
  //振り子の起点の座標と腕の長さ
  p = new Pendulum(new PVector(width/2, 10), 125);
}
 
void draw() {
  background(255);
  p.go();
}
class Pendulum{
  PVector location;  //球の座標
  PVector origin;  //振り子の起点の座標
  float r;  //腕の長さ
  float angle;  //振り子の腕の角度
  float aVelocity;  //角速度
  float aAcceleration;  //角加速度
  float damping;  //任意の減衰量
  float gravity = 0.4;  //重力
  
  //コンストラクタ
  Pendulum(PVector origin_, float r_){
    origin = origin_.copy();
    location = new PVector();
    r = r_;

    angle = PI/4;  //角度の初期値:45度
    aVelocity = 0.0;
    aAcceleration = 0.0;
    damping = 0.99;
  }
  
  //実行
  void go(){
    update();
    display();
  }
  
  //角度の値を更新
  void update(){
    aAcceleration = (-1 * gravity / r) * sin(angle);
    aVelocity += aAcceleration;
    angle += aVelocity;
    
    aVelocity *= damping;  //速度を減衰
  }
  
  //図形の描画
  void display(){
    //球の座標
    location.set(r*sin(angle), r*cos(angle), 0);
    location.add(origin);
    
    //振り子の描画
    stroke(0);
    strokeWeight(2);
    fill(175);
    line(origin.x, origin.y, location.x, location.y);
    ellipse(location.x, location.y, 32, 32);    
  }  
}

まとめ

「The Nature of Code」から振り子について取り上げました。振り子にかかる力を計算して、振り子をシミュレーションしました。引き続き、「The Nature of Code」の内容を勉強します。

参考書籍

Javaの勉強にもなるので一石二鳥です。

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