LoginSignup
1
0
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

p5.js で WEBGLモードの3次元空間にランダムに球を配置する(+ クラスフィールド・プライベートプロパティを使う)

Last updated at Posted at 2024-01-23

今回の内容

今回の内容は、タイトルのとおりです。

以下のような見た目の描画を行ってみます。

image.png

上記は WEBGLモードを使って描画していますが、フラットな色を使っているので、3次元的な配置での見た目の立体感はないです。今回、Z軸方向の奥行きは、個々の球の描画サイズに影響を及ぼすだけのものとなっていますが、以下のような動きをつける時には、奥行き方向を使った位置の処理が活きてくると思います。

作ったもの

プログラム

今回作ったプログラムの内容は、以下のとおりです。

const balls = [];
const count = 100;

function setup() {
  createCanvas(550, 400, WEBGL);
  colorMode(HSB, 360, 100, 100, 100);

  for (let i = 0; i < count; i++) {
    balls.push(new Ball());
  }

  background(0);

  for (const b of balls) {
    b.display();
  }
}

class Ball {
  #factor = random(0, 3, 0.5);
  #position = createVector(
    random(-width / 2, width / 2),
    random(-height / 2, height / 2),
    random(-width * this.#factor, width * this.#factor)
  );
  #color = [random(100, 300), random(60, 90), 100];
  #size = random(10, 15);

  display() {
    noStroke();
    fill(this.#color);
    push();
    translate(this.#position.x, this.#position.y, this.#position.z);
    sphere(this.#size);
    pop();
  }
}

補足

3次元的な配置

今回行った球の配置で、3次元的にランダムに配置する際には、createVector() で位置を決めています。具体的には、x・y・z の 3つの軸に対してランダムな座標を生成しています。

クラスを作成する部分

クラスを作成する部分は、ES2022 から使えるようになったクラスフィールド・プライベートフィールドを使ってみています。今回のシンプルな例だと、これらを使う意味はあまりないのですが、後々の追加実装で役立つかも知れないという想定で、これらを使ってみました。

●パブリッククラスフィールド - JavaScript | MDN
 https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes/Public_class_fields

●プライベートプロパティ - JavaScript | MDN
 https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes/Private_properties

1
0
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
1
0