xxxxxxxxxx
146
// https://codepen.io/DonKarlssonSan/pen/BopXpq
// https://editor.p5js.org/codingtrain/sketches/XpS9wGkbB
// https://medium.com/@jason.webb/simulating-dla-in-js-f1914eb04b1d
let off;
let trees = [];
let walkers = [];
let grid;
const start_radius = 4;
const shrink = 0.995;
let radius;
let iterations = 1000;
let maxWalkers = 50;
function setup() {
createCanvas(800, 800);
background(20);
radius = start_radius;
off = width * 0.1;
let x = off;
noStroke();
fill(color(0, 0, 40));
rect(0, 0, off, height);
fill(color(0, 0, 220));
rect(off, 0, width - 2 * off, height);
fill(color(0, 0, 80));
rect(width - off, 0, off, height);
stroke(220);
for (let y = 2 * off; y < height; y += off / 2) {
line(0, y, x, y - off);
line(x, y - off, width - off, y - off);
line(width - off, y - off, width, y - 2 * off);
// if (random() > 0.2 && start_pts.length < 50) {
let _x = random(x, width - off);
let _y = y - off;
trees.push([
{
pos: createVector(_x, _y),
// x: _x,
// y: _y,
radius: start_radius,
},
]);
// }
}
fill(220);
noStroke();
for (let t of trees) {
circle(t[0].pos.x, t[0].pos.y, t[0].radius * 2);
}
radius *= shrink;
for (let i = 0; i < maxWalkers; i++) {
walkers.push(new Walker());
radius *= shrink;
}
}
function draw() {
for (let n = 0; n < iterations; n++) {
for (let i = walkers.length - 1; i >= 0; i--) {
let w = walkers[i];
// walk
w.walk();
// check stuck
let tree = w.checkStuck(trees);
if (tree != null) {
tree.push({ pos: createVector(w.pos.x, w.pos.y), radius: w.radius });
circle(w.pos.x, w.pos.y, w.radius * 2);
walkers.splice(i, 1);
}
// draw on tree if stuck and splice
}
}
if (walkers.length == 0) {
console.log("done");
noLoop();
} else {
let r = walkers[walkers.length - 1].radius;
while (walkers.length < maxWalkers && radius > 1) {
radius *= shrink;
walkers.push(new Walker());
}
}
}
class Walker {
constructor(x, y) {
if (arguments.length == 2) {
this.pos = createVector(x, y);
this.stuck = true;
} else {
// let xs = [];
// for (let t of tree) xs.push(t.pos.x);
this.pos = createVector(random(width),random(height));
// let x = random(xs);
// x += random(-5,5);
// this.pos = createVector(x, random(height));
this.stuck = false;
}
this.radius = radius;
}
walk() {
let vel = p5.Vector.random2D();
this.pos.add(vel);
this.pos.x = constrain(this.pos.x, 0, width);
this.pos.y = constrain(this.pos.y, 0, height);
}
checkStuck(others) {
for (let o of others) {
for (let o2 of o) {
let d = distSquared(this.pos, o2.pos);
if (
d <
this.radius * this.radius +
o2.radius * o2.radius +
2 * o2.radius * this.radius
) {
this.stuck = true;
return o;
}
}
}
return null;
}
}
function distSquared(a, b) {
// console.log(a,b)
let dx = b.x - a.x;
let dy = b.y - a.y;
return dx * dx + dy * dy;
}