Chapter 43

# ランダムウォーク

miku
2021.11.15に更新
このチャプターの目次

## ランダムウォーク

``````const iterations = 20;
let x, y;

function setup() {
createCanvas(windowWidth, windowHeight);
stroke(240);

x = floor(width / 2);
y = floor(height / 2);
}

function draw() {
for (let i = 0; i < iterations; i++) {
walk();
}
}

function walk() {
x += random([-1, 1]);
y += random([-1, 1]);

point(x, y);
}
``````

## ランダムウォーク 2

``````const iterations = 60;
const n = 100;
let points;

function setup() {
createCanvas(windowWidth, windowHeight);

points = [];
for (let i = 0; i < n; i++) {
const x = random(width);
const y = random(height);
const c = color(random(256), random(256), random(256));

points.push({ x, y, color: c });
}
}

function draw() {
for (let i = 0; i < iterations; i++) {
for (const p of points) {
walk(p);
}
}
}

function walk(p) {
p.x += random([-1, 1]);
p.y += random([-1, 1]);

stroke(p.color);
point(p.x, p.y);
}
``````

## 移動する量を変える

``````const iterations = 20;
const size = 4;
let x, y;

function setup() {
createCanvas(windowWidth, windowHeight);
stroke(240);
noFill();

x = floor(width / 2);
y = floor(height / 2);
}

function draw() {
walk();
}

function walk() {
const tx = x + random([-size, size]);
const ty = y + random([-size, size]);

line(x, y, tx, ty);

x = tx;
y = ty;
}
``````