xxxxxxxxxx
98
let capture;
let particles = [];
let particleCount = 1000;
let flowField;
let scl = 20;
let cols, rows;
function setup() {
createCanvas(640, 480);
capture = createCapture(VIDEO);
capture.size(640, 480);
capture.hide();
cols = floor(width / scl);
rows = floor(height / scl);
flowField = new Array(cols * rows);
for (let i = 0; i < particleCount; i++) {
particles[i] = new Particle();
}
background(0);
}
function draw() {
capture.loadPixels();
// Calculate flow field
let yoff = 0;
for (let y = 0; y < rows; y++) {
let xoff = 0;
for (let x = 0; x < cols; x++) {
let index = x + y * cols;
let angle = noise(xoff, yoff, frameCount * 0.01) * TWO_PI * 4;
let v = p5.Vector.fromAngle(angle);
v.setMag(1);
flowField[index] = v;
xoff += 0.1;
}
yoff += 0.1;
}
for (let particle of particles) {
particle.follow(flowField);
particle.update();
particle.edges();
particle.show();
}
}
class Particle {
constructor() {
this.pos = createVector(random(width), random(height));
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.maxSpeed = 4;
this.prevPos = this.pos.copy();
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.mult(0);
}
follow(vectors) {
let x = floor(this.pos.x / scl);
let y = floor(this.pos.y / scl);
let index = x + y * cols;
let force = vectors[index];
this.applyForce(force);
}
applyForce(force) {
this.acc.add(force);
}
show() {
let pixelColor = capture.get(floor(this.pos.x), floor(this.pos.y));
stroke(pixelColor[0], pixelColor[1], pixelColor[2], 50);
strokeWeight(1);
line(this.pos.x, this.pos.y, this.prevPos.x, this.prevPos.y);
this.updatePrev();
}
updatePrev() {
this.prevPos.x = this.pos.x;
this.prevPos.y = this.pos.y;
}
edges() {
if (this.pos.x > width) this.pos.x = 0;
if (this.pos.x < 0) this.pos.x = width;
if (this.pos.y > height) this.pos.y = 0;
if (this.pos.y < 0) this.pos.y = height;
}
}