xxxxxxxxxx
116
let w;
let h;
let spacing;
let cols;
let rows;
let grid;
let particles;
let noiseOffset = 0;
function computeVector(x, y, z) {
const s = 0.02;
const v = p5.Vector.fromAngle(noise(x * s, y * s, z * s) * TWO_PI);
return p5.Vector.mult(v, 2);
}
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.prevPos = this.pos.copy();
this.vel = createVector(0, 0);
this.col = color(random([312, 260]), 100, 100, 0.05);
}
applyForce(f) {
this.vel.add(f);
// this.vel.limit(100);
}
update() {
this.prevPos = this.pos.copy();
this.pos.add(this.vel);
this.vel.mult(0);
const gap = 5;
let outside = false;
if (this.pos.x < -gap) {
this.pos.x = width + gap;
outside = true;
} else if (this.pos.x >= width + gap) {
this.pos.x = -gap;
outside = true;
}
if (this.pos.y < -gap) {
this.pos.y = height + gap;
outside = true;
} else if (this.pos.y >= height + gap) {
this.pos.y = -gap;
outside = true;
}
if (outside) {
this.prevPos = this.pos.copy();
}
}
show() {
stroke(this.col);
strokeWeight(1);
// point(this.pos.x, this.pos.y);
line(this.prevPos.x, this.prevPos.y, this.pos.x, this.pos.y);
}
}
function setup() {
// createCanvas(600, 500);
createCanvas(720, 1600);
// createCanvas(windowWidth, windowHeight);
colorMode(HSB);
spacing = 5;
cols = ceil(width / spacing);
rows = ceil(height / spacing);
grid = Array.from({ length: rows }, (_, y) =>
Array.from({ length: cols }, (_, x) => {
return computeVector(x, y, noiseOffset);
})
);
particles = Array.from({ length: 5000 }, (_, i) => {
return new Particle(random(width), random(height));
});
background(0);
}
function draw() {
// Update flow field
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
grid[y][x] = computeVector(x, y, noiseOffset);
}
}
noiseOffset += 0.05;
// Vectors
// stroke(255, 20);
// strokeWeight(2);
// for (let y = 0; y < rows; y++) {
// for (let x = 0; x < cols; x++) {
// const v = grid[y][x];
// const a = createVector(
// x * spacing + spacing / 2,
// y * spacing + spacing / 2
// );
// const b = p5.Vector.add(a, p5.Vector.mult(v, 10));
// line(a.x, a.y, b.x, b.y);
// }
// }
// Particles
for (let p of particles) {
const x = constrain(ceil((p.pos.x / width) * cols), 0, cols - 1);
const y = constrain(ceil((p.pos.y / height) * rows), 0, rows - 1);
const f = grid[y][x];
p.applyForce(f);
p.update();
p.show();
}
}