xxxxxxxxxx
88
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
let moverA;
let moverB;
function setup() {
createCanvas(640, 360);
// A large Mover on the left side of the window
moverA = new Mover(200, 30, 10);
// A smaller Mover on the right side of the window
moverB = new Mover(440, 30, 2);
createP('Click mouse to apply wind force.');
}
function draw() {
background(51);
let gravity = createVector(0, 0.1);
let gravityA = p5.Vector.mult(gravity, moverA.mass);
moverA.applyForce(gravityA);
let gravityB = p5.Vector.mult(gravity, moverB.mass);
moverB.applyForce(gravityB);
if (mouseIsPressed) {
let wind = createVector(0.1, 0);
moverA.applyForce(wind);
moverB.applyForce(wind);
}
moverA.update();
moverA.display();
moverA.checkEdges();
moverB.update();
moverB.display();
moverB.checkEdges();
}
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
class Mover {
constructor(x, y, m) {
this.mass = m;
this.radius = m * 8;
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
}
applyForce(force) {
let 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 * 2);
}
checkEdges() {
if (this.position.x > width - this.radius) {
this.position.x = width - this.radius;
this.velocity.x *= -1;
} else if (this.position.x < this.radius) {
this.position.x = this.radius;
this.velocity.x *= -1;
}
if (this.position.y > height - this.radius) {
this.position.y = height - this.radius;
this.velocity.y *= -1;
}
}
}