p5.js入門記 -その1雪を降らせる-


はじめに

p5.jsの入門を終わらせた後、実際に作品を作っていこうという記事です。
探り探りですが書いていこうと思います。

入門時に参考にしたもの一覧

雪を降らせる

冬なので雪を降らせてみたいと思いました。

【参考】

【使用素材】
by いらすとや

成果物

コード

雪部分はほぼサンプルコード通りですが、粒の大きさなど適宜調整しました。

sample.js
let snowflakes = []; // array to hold snowflake objects
var bg;
var img;

function setup() {
  createCanvas(720, 400);
  fill(240);
  noStroke();
  bg = loadImage("bg_snow_jutaku.jpg");
  img = loadImage("kids_hashirimawaru_snow.png");
}

function draw() {
  image(bg,0,0);
  image(img, width/3, 80, img.width/2, img.height/2);

  let t = frameCount / 60; // update time

  // create a random number of snowflakes each frame
  for (var i = 0; i < random(10); i++) {
    snowflakes.push(new snowflake()); // append snowflake object
  }

  // loop through snowflakes with a for..of loop
  for (let flake of snowflakes) {
    flake.update(t); // update snowflake position
    flake.display(); // draw snowflake
  }
}

// snowflake class
function snowflake() {
  // initialize coordinates
  this.posX = 0;
  this.posY = random(-50, 0);
  this.initialangle = random(0, 2 * PI);
  this.size = random(6, 12);

  // radius of snowflake spiral
  // chosen so the snowflakes are uniformly spread out in area
  this.radius = sqrt(random(pow(width / 2, 2)));

  this.update = function(time) {
    // x position follows a circle
    let w = 0.6; // angular speed
    let angle = w * time + this.initialangle;
    this.posX = width / 2 + this.radius * sin(angle);

    // different size snowflakes fall at slightly different y speeds
    this.posY += pow(this.size, 0.5);

    // delete snowflake if past end of screen
    if (this.posY > height) {
      let index = snowflakes.indexOf(this);
      snowflakes.splice(index, 1);
    }
  };

  this.display = function() {
    ellipse(this.posX, this.posY, this.size);
  };
}

おわりに

また次回、よろしくお願いします!