xxxxxxxxxx
// Configurable variables.
const CANVAS_SIZE = 400;
const MOVER_COUNT = 5;
const MOVER_LINE_COUNT = 20;
const COORD_FUZZ = 5;
const SQUARE_COUNT = 12;
const SQUARE_MIN_SIZE = 20;
const SQUARE_MAX_SIZE = 40;
const SQUARE_RADIUS_FUZZ = 2;
// A square is defined by a list [x, y, r].
// Squares is a list of squares.
// i.e. [square1, square2, ...]
const squares = [];
// A line is a list of 4 numbers: the coordinates which
// define two different points point of the line.
// e.g. [x1, y1, x2, y2]
// A mover is a list of lines.
// e.g. [line1, line2, ...];
// Movers is a list of movers.
// i.e. [mover1, mover2, ...]
const movers = [];
function setup() {
createCanvas(CANVAS_SIZE, CANVAS_SIZE);
// Setup colors and drawing settings.
stroke(255);
fill(255);
rectMode(CENTER);
// Create movers and squares.
for (let i = 0; i < MOVER_COUNT; i++) {
movers.push([]);
}
for (let i = 0; i < SQUARE_COUNT; i++) {
addSquare();
}
}
function draw() {
background(0, 0, 0, 130);
// Update movers and draw them.
for (let mover of movers) {
// Add a line to the end of the mover.
addLine(mover);
// If the mover has more lines than allowed, remove the first line.
if (mover.length > MOVER_LINE_COUNT) {
removeLine(mover);
}
// Draw all lines.
for (let l of mover) {
line(l[0], l[1], l[2], l[3]);
}
}
// Update squares and draw them.
for (let square of squares) {
moveSquare(square);
rect(square[0], square[1], square[2], square[2]);
}
}
function removeLine(mover) {
// Remove the first (at position 0) line of a mover.
mover.shift();
}
function addLine(mover) {
// Add a line at the end (last position) of a mover.
// Initialize the line.
const newLine = [0, 0, 0, 0];
if (mover.length > 0) {
// Mover has previous lines.
// This line should use the last line (the one at the end) and
// fuzz its coordinates by a bit.
const lastLine = mover[mover.length - 1];
for (let i = 0; i < 4; i++) {
newLine[i] = constrain(
lastLine[i] + random(-COORD_FUZZ, COORD_FUZZ), 0, CANVAS_SIZE);
}
} else {
// This is the first line.
// Its coordinates are random.
for (let i = 0; i < 4; i++) {
newLine[i] = random(0, CANVAS_SIZE);
}
}
// Add the line to the mover.
mover.push(newLine);
}
function addSquare() {
// Add a square to the squares.
squares.push([0, 0, 0]);
}
function moveSquare(square) {
// Move a square by fuzzing its coordinates and size.
square[0] = constrain(
square[0] + random(-COORD_FUZZ, COORD_FUZZ), 0, CANVAS_SIZE);
square[1] = constrain(
square[1] + random(-COORD_FUZZ, COORD_FUZZ), 0, CANVAS_SIZE);
square[2] = constrain(
square[2] + random(-SQUARE_RADIUS_FUZZ, SQUARE_RADIUS_FUZZ),
SQUARE_MIN_SIZE,
SQUARE_MAX_SIZE);
}