xxxxxxxxxx
64
let bodies,
forces,
previousMouseX,
previousMouseY;
function setup() {
createCanvas(400, 400);
bodies = [];
for (let i = 0; i < 10; i++) {
bodies.push(new Body(random(100, 800)));
}
forces = [
function(body) {
// Gravity
return p5.Vector.mult(createVector(0, 0.5), body.mass);
},
function(body) {
// Ground friction
let friction = createVector(0, 0);
if (height - (body.position.y + body.radius) < 1) {
friction = body.velocity.copy();
friction.normalize();
friction.mult(-1);
friction.setMag(0.2 * body.mass);
}
return friction;
},
function(body) {
// Air friction
friction = body.velocity.copy();
friction.normalize();
friction.mult(-1);
friction.setMag(0.1 * body.mass);
return friction;
}
];
previousMouseX = mouseX;
previousMouseY = mouseY;
}
function draw() {
background(22);
for (const body of bodies) {
for (const force of forces)
body.applyForce(force(body));
body.update();
body.edges();
body.show();
}
}
function mouseMoved() {
if (mouseIsPressed) {
for (const body of bodies) {
if (dist(body.x, body.y, mouseX, mouseY) <= body.radius) {
body.overwriteVelocity(p5.Vector.sub(createVector(mouseX, mouseY), createVector(previousMouseX, previousMouseY)));
body.update();
}
}
}
previousMouseX = mouseX;
previousMouseY = mouseY;
}