LoginSignup
3
4

p5.js の noise() で遊ぶ

Posted at

はじめに

たくさんのパーティクルが連続的に、かつそれぞれ独立して動くようなものを作りたいと思います。
Math.random() のような関数を使って、パーティクルの座標を動かしていってもいいのですが、それぞれの動きがバラバラすぎて、パーティクルの数を増やしていくと目にうるさくなってしまいます。

方法

Processing に用意されている noise() というメソッドを使います。
これは、パーリンノイズと呼ばれる、人間にとって自然なゆらぎに見える連続した数値を与えてくれるものです。

環境

editor.p5.js
p5.js: v1.9.3

本プロジェクトにIDEを使う利点が見出だせなかったので、今回は Processing (Java) ではなく p5.js で実装しました。

コード例

sketch.js
class DriftingPoint {
  constructor() {
    this.seed = random() * 10;
    this.noiseLevel = width >= height ? width : height;
    this.noiseScale = 0.0002;
  }
  
  draw() {
    this.update();
    point(this.x, this.y);
  }
  
  update() {
    this.x = this.noiseLevel * noise(frameCount * this.noiseScale + this.seed);
    this.y = this.noiseLevel * noise(frameCount * this.noiseScale + this.seed + 10000);
  }
} // class DriftingPoint


const pointList = [];

function setup() {
  createCanvas(400, 400);
  strokeWeight(10);
  
  for(let i=0; i<100; i++) {
    pointList.push(new DriftingPoint());
  }
}

function draw() {
  background(220);
  pointList.forEach(p => p.draw());
}

実行結果
20240517-214033.gif
この程度の散らばり具合だと、じつはランダムではないということがわかると思います。


上記のコードの3行目を以下のように変えて散らばり具合を大きくしてみます。

this.seed = random() * 1000;

結果は以下のとおりです。
20240517-214000.gif
それぞれが連続的に、とはいえいくらかの不規則性を持って動いているのがわかります。

余談

p5.js の実行画面を簡単に録画できる p5.capture というライブラリがとても便利で感動しました。
今後積極的に使っていきたいです。

あと、 class DriftingPoint 内で noiseScale を static プロパティとして宣言したかったのですが、
Class properties must be methods. Expected '(' but instead saw 'noiseScale'. と怒られてしまいました。クラスもスタティックプロパティを持つことができるという認識だったので、どうすればいいか調べてみましたが理由がよくわかりませんでした。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4