xxxxxxxxxx
91
// References: https://editor.p5js.org/codingtrain/sketches/tKBc2fP8r
let butterfly = [];
function setup() {
createCanvas(windowWidth, windowHeight);
// background(50);
for(let i = 0; i < 20; i++){
butterfly.push(new Butterfly(random(100, width-100), random(100, height - 100)));
}
// butterfly.push(new Butterfly(width/2, height/2));
}
function draw() {
background(29, 69, 110);
for (let i = butterfly.length - 1; i >= 0; i--) {
butterfly[i].display();
butterfly[i].flying();
let mouse = createVector(mouseX, mouseY);
// butterfly[i].attractedTo(mouse);
butterfly[i].repelledBy(mouse);
if(butterfly[i].pos.x <= 0 || butterfly[i].pos.x >= width || butterfly[i].pos.y <= 0 || butterfly[i].pos.y >= height) {
butterfly.splice(i, 1);
butterfly.push(new Butterfly(width/2, height/2));
}
}
}
class Butterfly {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(random(-2, 1), random(-2, 1));
this.acc = createVector();
// variables for the visuals
this.r = random(169, 252);
this.g = random(169, 252);
this.b = random(169, 252);
this.size = random(20, 40);
}
appliedForce(f) {
this.acc.add(f);
}
attractedTo() {
let target = createVector(width/2, height/2);
let attraction = p5.Vector.sub(target, this.pos);
attraction.mult(0.0001);
this.appliedForce(attraction);
}
flying() {
// this.vel.mult(-0.8);
this.vel.add(this.acc);
this.pos.add(this.vel);
}
repelledBy(target) {
let repulse = p5.Vector.sub(target, this.pos);
let distance = repulse.mag();
if (distance < 50) {
repulse.mult(-0.0001);
this.appliedForce(repulse);
}
}
display() {
// stroke(255);
noStroke();
fill(this.r, this.g, this.b, 200);
for(let dx = 0; dx <= 20; dx += 15) {
for(let dy = 0; dy <= 20; dy += 15){
ellipse(this.pos.x + dx, this.pos.y - dy, this.size);
}
}
}
}
function mousePressed() {
for(let i = 0; i < butterfly.length; i++){
butterfly[i].attractedTo();
}
}