xxxxxxxxxx
116
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for this video: https://youtu.be/flQgnCUxHlw
const r = 4;
const k = 30;
const grid = [];
const w = r / Math.sqrt(2);
const active = [];
let cols, rows;
let prevOrder = 0;
function adjust() {
resizeCanvas(windowWidth, windowHeight);
}
function windowResized() {
adjust();
}
function setup() {
createCanvas(400, 400);
adjust();
background(0);
strokeWeight(4);
colorMode(HSB);
// STEP 0
cols = floor(width / w);
rows = floor(height / w);
for (let i = 0; i < cols * rows; i++) {
grid[i] = undefined;
}
// STEP 1
const x = width / 2;
const y = height / 2;
const i = floor(x / w);
const j = floor(y / w);
const pos = createVector(x, y);
pos.order = 0;
grid[i + j * cols] = pos;
active.push(pos);
//frameRate(1);
}
function draw() {
clear();
if(frameRate() < 5){
noLoop();
//console.log(document.location.href);
return;
}
//noLoop();
for (let total = 0; total < 25; total++) {
if (active.length > 0) {
const randIndex = floor(random(active.length));
const pos = active[randIndex];
let found = false;
for (let n = 0; n < k; n++) {
const sample = p5.Vector.random2D();
const m = random(r, 2 * r);
sample.setMag(m);
sample.add(pos);
const col = floor(sample.x / w);
const row = floor(sample.y / w);
if (col > -1 && row > -1 && col < cols && row < rows && !grid[col + row * cols]) {
let ok = true;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const index = (col + i) + (row + j) * cols;
const neighbor = grid[index];
if (neighbor) {
const d = p5.Vector.dist(sample, neighbor);
if (d < r) {
ok = false;
}
}
}
}
if (ok) {
found = true;
sample.order = ++prevOrder;
grid[col + row * cols] = sample;
active.push(sample);
break;
}
}
}
if (!found) {
active.splice(randIndex, 1);
}
}
}
for (let i = 0; i < grid.length; i++) {
if (grid[i]) {
stroke(grid[i].order / 10 % 360, 100, 100);
strokeWeight(r * 0.5);
point(grid[i].x, grid[i].y);
}
}
// for (var i = 0; i < active.length; i++) {
// stroke(255, 0, 255);
// strokeWeight(1);
// point(active[i].x, active[i].y);
// }
//console.log(active.length);
}