xxxxxxxxxx
110
let points;
let numPoints;
let time;
let animationIndex;
function setup() {
createCanvas(400, 400);
animationIndex = 0;
points = [];
numPoints = 25;
for (let i = 0; i < numPoints; i++) {
let point = new Follow(random(0, width), random(0, height));
points.push(point);
}
}
function draw() {
background(220,255,255,100);
fill(255);
time += 0.01;
noStroke();
points.forEach((point, index) => {
if (animationIndex === 0) {
point.setPos(mouseX, mouseY);
} else if (animationIndex === 1) {
let pos = layoutCircle(points.length, 90, index);
point.setPos(pos.x + width / 2, pos.y + height / 2);
} else {
let pos = layoutGrid(points.length, 5, 5, 50, index);
point.setPos(pos.x + width / 2, pos.y + height / 2);
}
point.update();
//NOTE HERE! we're passing the point a function that tells
// it how to draw at the provided x, y position.
// notice how useful it is because we have acces here to variables like index to modify how we're drawing
point.draw((x, y) => {
if (animationIndex === 1) {
line(x, y, x + 25, y + 25);
} else if(animationIndex ===2) {
let step = (index + 1) / points.length;
ellipse(x, y, 25*step, 25*step);
} else {
ellipse(x, y, 25, 25);
}
});
});
}
function osc(scale) {
if (!scale) {
scale = 1;
}
return abs(sin(frameCount * 0.01 * scale));
}
function mousePressed() {
animationIndex += 1;
animationIndex = animationIndex % 3;
}
function layoutCircle(count, scale, index) {
let inc = map(index, 0, count, 0, TWO_PI);
let x = sin(inc * 3 * osc()) * scale;
let y = cos(inc * osc()) * scale;
return ({x, y});
}
function layoutGrid(count, cols, rows, scale, index) {
let x = ((index + 1) % rows) * scale;
let y = ceil(((index + 1) / (count)) * cols) * scale;
x -= scale * rows / 2 - scale / 2;
y -= scale * cols / 2 + scale / 2;
return ({x, y});
}
class Follow {
constructor(x, y) {
this.currX = x;
this.currY = y;
this.finalX = 0;
this.finalY = 0;
this.speed = random(0.1, .2);
}
setPos(x, y) {
this.finalX = x;
this.finalY = y;
}
update() {
this.currX = lerp(this.currX, this.finalX, this.speed);
this.currY = lerp(this.currY, this.finalY, this.speed);
}
draw(shape) {
//NOTE HERE. we're calling the function that's passed in
// and we're providing the funcion its x and y value
shape(this.currX, this.currY);
}
}