xxxxxxxxxx
67
//modified from Dan Shiffman Nature of Code
let movers = [];
function setup() {
createCanvas(640, 360);
for (let i = 0; i < 20; i++) { //initializing an array of 20 movers
movers[i] = new Mover(random(0.1, 5), 0, 0);
}
}
function draw() {
background(255);
for (let i = 0; i < movers.length; i++) { //this runs in a loop, so that it affects all movers individually
let wind = createVector(0.01, 0);
let gravity = createVector(0, 0.1);
movers[i].applyForce(wind);
movers[i].applyForce(gravity);
movers[i].update();
movers[i].display();
movers[i].checkEdges();
}
}
class Mover {
constructor() {
this.radius = random(10,60);
this.mass = map(this.radius,10,60,0,1);
this.position = createVector(random(width), random(height));
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
}
applyForce(force) {
var f = p5.Vector.div(force, this.mass);
this.acceleration.add(f);
}
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
display() {
stroke(0);
strokeWeight(2);
fill(255, 127);
ellipse(this.position.x, this.position.y, this.radius);
}
checkEdges() {
if (this.position.x > width) {
this.position.x = width;
this.velocity.x *= -1;
} else if (this.position.x < 0) {
this.velocity.x *= -1;
this.position.x = 0;
}
if (this.position.y > height) {
this.velocity.y *= -1;
this.position.y = height;
}
}
}