xxxxxxxxxx
70
let movers = [];
function setup() {
createCanvas(560,390);
for (let i = 0; i < 20; i++) {
// initialize objects with random mass and start at 0,0
movers[i] = new Mover(random(0.1,5),0,0);
}
}
function draw() {
background(220);
for (let i = 0; i < movers.length; i++) {
let wind = createVector(0.01,0);
let gravity = createVector(0,0.1); // make up two forces
// apply both forces to each objects
movers[i].applyForce(wind);
movers[i].applyForce(gravity);
movers[i].update();
movers[i].display();
movers[i].checkEdges();
}
}
class Mover {
constructor(m, x, y) {
// mass and location initialized via arguments now
this.mass = m;
this.location = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
}
applyForce(force) {
// acceleration = force/mass
let f = p5.Vector.div(force, this.mass);
this.acceleration.add(f);
}
update() {
this.velocity.add(this.acceleration);
this.location.add(this.velocity);
this.acceleration.mult(0);
}
display() {
stroke(0);
strokeWeight(2);
fill(63,63,147,150);
// scaling the size according to mass
// the smaller circles reach the right of the window faster than the larger ones
// because acceleration = force/mass, the larger the mass, the smaller the acceleration
ellipse(this.location.x, this.location.y, this.mass*16, this.mass*16);
}
// object bounces when it hits the edge of window
checkEdges() {
if (this.location.x > width) {
this.location.x = width;
this.velocity.x *= -1;
} else if (this.location.x < 0) {
this.velocity.x *= -1;
this.location.x = 0;
}
if (this.location.y > height) {
this.velocity.y *= -1; // reverse the direction of object when it reaches the edge
this.location.y = height;
}
}
}