【p5.js】randomとnoiseの比較のつづき

Learning of p5.js

Posted by 51n1 on 24 Apr, 2020

p5.js tutorial in the nature of code

I.4: Graphing 1D Perlin Noise - Perlin Noise and p5.js Tutorial by Daniel Shiffman.

シフマン先生のチュートリアルを参考にサンプルを2つ作成。1つ目はランダムウォークさせてみたもの。なんとなくnoiseの特徴(値が中央値に寄る)が出ている感じがする。2つ目のサンプルはチュートリアルと同様にX軸上に1次元の線を描画し比較したもの。

p5.js official reference:
noise()
random()

p5.js sample 1: Random Walk

// Sample Code 1
let rx, ry;
let xoff1 = 0;
let xoff2 = 10000;

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(255);
  fill(255);
  stroke(0, 100);
  rx = random(0, width/2);
  ry = random(0, height);
  textSize(32);
  textStyle(BOLD);
  textAlign(CENTER, CENTER);
}

function draw() {
  rx += random(-10, 10);
  rx = constrain(rx, 0, width/2)
  ry += random(-10, 10);
  ry = constrain(ry, 0, height);
  ellipse(rx, ry, 24, 24);
  fill(0);
  text("Random", width*1/4, height/2);
  fill(255);

  let nx = map(noise(xoff1), 0, 1, width/2, width);
  let ny = map(noise(xoff2), 0, 1, 0, height);
  xoff1 += 0.01;
  xoff2 += 0.01;
  ellipse(nx, ny, 24, 24);
  fill(0);
  text("Noise", width*3/4, height/2);
  fill(255);

  noFill();
  rect(0, 0, width, height);
  fill(255);
}

p5.js sample 2: Graph 1D

// Sample Code 2
let inc = 0.01;
let start = 0;

function setup() {
  createCanvas(windowWidth, windowHeight);
  fill(255);
  stroke(0);
  textSize(32);
  textStyle(BOLD);
  textAlign(CENTER, CENTER);
}

function draw() {
  background(51);
  stroke(255);
  noFill();

  // Random Part
  beginShape();
  for (let x = 0; x < width/2; x++) {
    let y = random(height);
    vertex(x, y);
  }
  endShape();
  fill(51);
  text("Random", width*1/4, height/2);
  noFill();

  // Noise Part
  beginShape();
  let xoff = start;
  for (let x = width/2; x < width; x++) {
    let n = map(noise(xoff), 0, 1, 0, height);
    let s = map(sin(xoff), -1, 1, -50, 50);
    let y = n + s;
    vertex(x, y);
    xoff += inc;
  }
  endShape();
  fill(51);
  text("Noise", width*3/4, height/2);
  noFill();

  start += inc;

}