xxxxxxxxxx
124
// Change this variable to change the granularity of the pixel field
var inc = 0.5;
// How many pixels to one vector
var scl = 30;
var cols, rows;
var zoff = 0;
// Store the direction vectors in an array
var flowfield = [];
// Particle array
var particles = [];
let record = false;
let cnv;
function setup() {
cnv = createCanvas(400, 400, SVG);
cols = floor(width / scl);
rows = floor(height / scl);
flowfield = new Array(cols * rows);
for (var i = 0; i < 60; i++) {
particles[i] = new Particle();
}
}
function draw() {
background(255);
var yoff = 0;
for (var x = 0; x < rows; x++) {
var xoff = 0;
for (var y = 0; y < cols; y++) {
// Pick the angels of the vectors
var angle = noise(xoff, yoff, zoff) * TWO_PI * 4;
var v = p5.Vector.fromAngle(angle);
// The following line changes how the particles follow the vector path
v.setMag(1);
var index = x + y * cols;
flowfield[index] = v;
// push();
// translate(x * scl, y * scl);
// rotate(v.heading());
// stroke(0, 50);
// strokeWeight(1);
// line(0, 0, scl, 0);
// pop();
xoff += inc;
}
yoff += inc;
zoff += 0.0003;
}
// Update the particles
for (var i = 0; i < particles.length; i++) {
particles[i].follow(flowfield);
particles[i].update();
particles[i].edges();
particles[i].show();
}
if (record == true) {
save("mySVG.svg"); // give file name
print("saved svg");
record = false;
}
}
function mousePressed() {
record = true;
}
function Particle() {
this.pos = createVector(random(width), random(height));
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.maxspeed = 4;
this.update = function() {
this.vel.add(this.acc);
this.vel.limit(this.maxspeed);
this.pos.add(this.vel);
this.acc.mult(0);
}
this.follow = function(vectors) {
// Scale to columns and rows
var x = floor(this.pos.x / scl);
var y = floor(this.pos.y / scl);
// Formula to take 2D value and translate to 1D array
var index = x + y * cols;
// Take the given vector at that location and apply it as a force
var force = vectors[index];
this.applyForce(force);
}
this.applyForce = function(force) {
this.acc.add(force);
}
this.show = function() {
stroke(0);
strokeWeight(1);
ellipse(this.pos.x, this.pos.y, 10, 10);
}
this.edges = function() {
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;
}
}