xxxxxxxxxx
81
let circles = [];
let gravity = true;
function setup() {
createCanvas(600, 600);
for (let i = 0; i < 50; i++) {
circles.push(new Mover(random(width), random(height), random (10, 50)));
}
noFill();
}
function draw() {
background(255);
for (let i = 0; i < circles.length; i++) {
circles[i].run();
if (gravity)
circles[i].addForce(0,0.1);
}
}
// when the mouse is pressed assign a random x & y force
function mousePressed() {
for (let i = 0; i < circles.length; i++) {
circles[i].addForce(random(-5, 5),random(-5, 5));
}
}
class Mover {
constructor(_x, _y, _s) {
this.x=_x;
this.y=_y;
this.xVelocity = 0;
this.yVelocity = 0;
this.xAcceleration = random(-10, 10);
this.yAcceleration = random(-10, 10);
this.size = _s;
}
update() {
this.xVelocity += this.xAcceleration;
this.yVelocity += this.yAcceleration;
this.x += this.xVelocity;
this.y += this.yVelocity;
this.xVelocity *= 0.98;
this.yVelocity *= 0.98;
this.xAcceleration = 0;
this.yAcceleration = 0;
}
addForce(forceX, forceY){
this.xAcceleration = forceX/(this.size*0.01);
this.yAcceleration = forceY/(this.size*0.01);
}
display() {
circle(this.x, this.y, this.size);
}
checkEdges() {
if (this.y > height+this.size/2 && !gravity) {
this.y = -this.size/2;
}
if (this.y < -this.size/2) {
this.y = height+this.size/2;
}
if (this.x > width+this.size/2) {
this.x = -this.size/2;
}
if (this.x < -this.size/2) {
this.x = width+this.size/2;
}
}
run(){
this.update();
this.display();
this.checkEdges();
}
}