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

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

 メニュー

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

Processing:オシレーターオブジェクト:振動

「The Nature of Code」から単振動について取り上げます。単振動の出力値を振り子のx座標とy座標に適用します。また、振動をオシレータークラスとして書き出します。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

本記事の参考書籍は以下です。

オシレータークラス

前回の記事(Processingにおける単振動:振幅と周期)を元に振動をオシレータークラスとして書き出します。

x座標とy座標の値に振動を適用させます。

class Osillator{
  PVector angle;  //角度
  PVector velocity;  //速度
  PVector amplitude;  //振幅

  Osillator(){
    angle = new PVector();
    velocity = new PVector(random(-0.05, 0.05), random(-0.05, 0.05));
    amplitude = new PVector(random(width/2), random(height/2));
  }

  //振動
  void oscillate(){
    angle.add(velocity);
  }

  //描画
  void display(){
    float x = cos(angle.x) * amplitude.x;
    float y = sin(angle.y) * amplitude.y;

    pushMatrix();
    stroke(0);
    strokeWeight(2);
    fill(127);

    translate(width/2, height/2);
    line(0, 0, x, y);
    ellipse(x, y, 24, 24);
    popMatrix();
  }
}
//Oscillator objects
Osillator[] oscillators = new Osillator[10];

void setup() {
  size(200, 200);
  //初期化、生成
  for(int i = 0; i < oscillators.length; i++){
    oscillators[i] = new Osillator();
  }
}

void draw() {
  background(255);

  for(int i = 0; i < 10; i++){
    oscillators[i].oscillate();
    oscillators[i].display();
  }
}

プログラムの解説

PVectorを利用して、オシレータークラスを作ります。

class Osillator{
  PVector angle;  //角度
  PVector velocity;  //速度
  PVector amplitude;  //振幅

  Osillator(){
    angle = new PVector();
    velocity = new PVector(random(-0.05, 0.05), random(-0.05, 0.05));
    amplitude = new PVector(random(width/2), random(height/2));
  }
  ...
}

まとめ

「The Nature of Code」から単振動について取り上げました。今回は、単振動の出力値を振り子のx座標とy座標に適用しました。また、振動をオシレータークラスとして書き出しました。引き続き、「The Nature of Code」の内容を勉強します。

参考書籍

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

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