xxxxxxxxxx
153
// 2 dividers
let x1, x2;
// Speeds of dividers
let xspeed1, xspeed2;
// Min/Max colors
let LOW = 0;
let HIGH = 255;
// Starting alpha
let a = LOW;
// Alpha speed
let aspeed = 3;
// Starting bg color
let bg = HIGH;
// Alpha margin
let am = 0;
// What counts as not moving
let VEL_TH = 5;
// Average midpoints
let mids = [];
// Timespan for smoothing in seconds
let ts = 60 * 5;
// Average movement in x-direction
let xvel = 10;
// 2 positions
let p1, p2;
// Have we updated the speed
let updated = false;
function setup() {
createCanvas(windowWidth, windowHeight);
noStroke();
//noCursor();
randomSeed(0);
// Initialize 2 positions
p1 = {
x: width * 0.25,
y: height * 0.25
}
p2 = {
x: width * 0.75,
y: height * 0.75
}
reset();
}
function reset() {
// Fade-in all over again
a = LOW;
// Create a random middle
x1 = width * random(0.5);
x2 = width - x1;
// Need to update speeds again
updated = false;
}
function updateMidpoint() {
// Calculate the mid-point between 2 points
let mid = {
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2
}
// Store this frame's midpoint
mids.push(mid);
// Only keep them for so long
if (mids.length > ts) mids.shift();
// Draw the people
fill('red');
ellipse(p1.x, p1.y, 10, 10);
ellipse(p2.x, p2.y, 10, 10);
// Draw the midpoint
fill('blue');
ellipse(mid.x, mid.y, 20, 20);
}
function updateSpeeds() {
// Add up x-velocity over time
xvel = 0;
for (let m in mids) {
if (m > 0) {
let pmid = mids[m - 1];
let mid = mids[m];
xvel += mid.x - pmid.x;
}
}
// Don't do anything if we're not moving
if (abs(xvel) < VEL_TH) {
xspeed1 = 0;
xspeed2 = 0;
return;
}
// Calculate a random destination on the edges of the space
let dmult = xvel > 0 ? random(0.75, 1) : random(0.25);
let dest = width * dmult;
// Calculate distance to destination
let dx1 = dest - x1;
let dx2 = dest - x2;
// Calculate pace based on xvel
let pace = 5000 / abs(xvel);
// Speeds are normalized so they arrive together
xspeed1 = dx1 / pace; //random(1) > 0.5 ? -speed : speed;
xspeed2 = dx2 / pace; //xspeed1 > 0 ? -speed : speed;
// Don't update speed anymore
updated = true;
}
function draw() {
background(bg);
// Is the background white or black?
// Make it the oppposite color
fill(bg > LOW ? LOW : HIGH, a);
rect(0, 0, x1, height);
rect(x2, 0, width - x2, height);
a += aspeed;
if (a > HIGH + am || a < LOW - am) {
if (!updated) updateSpeeds();
x1 += xspeed1;
x2 += xspeed2;
if ((x1 > width || x1 < 0) || (x2 > width || x2 < 0)) {
if (x1 > width || x2 < 0) {
// If the background was white, make it black
bg = bg > LOW ? LOW : HIGH;
}
reset();
}
}
// Calculate midpoint
updateMidpoint();
}
// Move the closest point with the mouse
// mouse is being dragged
function mouseDragged() {
let d1 = dist(mouseX, mouseY, p1.x, p1.y);
let d2 = dist(mouseX, mouseY, p2.x, p2.y);
if (d1 < d2) {
p1.x = mouseX;
p1.y = mouseY;
} else {
p2.x = mouseX;
p2.y = mouseY;
}
}