fbpx

Processingにおける回転・振動の実装 Part.3 振動

Part.2に続いて、今回はProcessingによって「振動」の表現を解説します。

振動の実装

1. 振動とは?

振動は、ある定位置から物体が時間に従って周期的に動く現象を指します。振動の一例として、振り子や弦の振動があります。振動は、振幅、周期、位相、角速度などで特徴付けられます。

  • 振幅(Amplitude): 定位置からの最大の偏移。
  • 周期(Period): 一つの完全な振動にかかる時間。
  • 角速度(Angular frequency)ω : 角度が時間単位で変化する速さ。周期Tとの関係は、ω = 2π/ T
  • ↑の式はTがωの角速度で2πラジアン分進むのにかかる時間(=周期)と考えれば良い

2. 単振動のコード例

単振動は、時間に対して物体の位置が正弦波または余弦波の形で変動する振動です。以下は、Processingを使った単振動の簡単なコード例です。

float amplitude = 50.0; // 振幅
float angularFrequency = 0.1; // 角速度

void setup() {
  size(400, 200);
}

void draw() {
  background(255);
  float x = width / 2;
  float y = height / 2 + sin(millis() * angularFrequency) * amplitude; // 単振動
  
float amplitude = 50.0; // 振幅
float angularFrequency = 0.1; // 角速度

void setup() {
  size(400, 200);
  frameRate(5); //目視しやすいようにフレームレートを5に設定
}

void draw() {
  background(255);
  float x = width / 2;
  float y = height / 2 + sin(millis() * angularFrequency) * amplitude; // 単振動

  ellipse(x, y, 20, 20); // 振動する円を描画
}

このコードは、画面の中央にある点が、垂直方向に正弦波の形で振動します。

3. Oscillatorオブジェクト(振幅・角速度・周期をもつ)

Oscillatorオブジェクトを定義し、それが振幅、角速度、周期を持つようにすることで、複雑な振動パターンを簡単に実装できます。

※Oscillatorは振動子という意味で、この名前自体は別の名前でも良い

以下は、Oscillatorクラスの定義と、そのオブジェクトの使用例です。

// Oscillatorクラス定義
class Oscillator {
  float amplitude; // 振幅
  float angularFrequency; // 角速度
  float period; // 周期
  
  Oscillator(float amplitude, float angularFrequency) {
    this.amplitude = amplitude;
    this.angularFrequency = angularFrequency;
    this.period = TWO_PI / angularFrequency; // 周期の計算
  }
  
  float oscillate(float time) {
    return sin(time * angularFrequency) * amplitude; // 単振動
  }
}

//メインプログラム
void setup() {
  size(400, 200);
}

void draw() {
  background(255);
  Oscillator osc = new Oscillator(50, 0.1); // 振幅50、角速度0.1のOscillatorオブジェクト
  
  float x = width / 2;
  float y = height / 2 + osc.oscillate(millis()); // Oscillatorオブジェクトを用いて振動
  
  ellipse(x, y, 20, 20); // 振動する円を描画
}

>> Part.4へ続く

演習

  1. Oscillatorオブジェクトをx-y両軸で振動させるように修正してみてください。
  2. Oscillatorオブジェクトに角加速度を追加し、振動速度(角速度)が時間変化するようにしてください。
  3. Oscillatorオブジェクトの配列を作り、連動して動かすことで規則的なパターンを生成してください。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA