xxxxxxxxxx
let balls, i;
function setup() {
createCanvas(windowWidth, windowHeight);
init();
}
function init() {
balls = [];
i = 0;
background(255);
balls[i] = new Ball();
}
function draw() {
background(255);
if (i == 0){
textSize(20);
fill(0);
textAlign(CENTER,CENTER);
text('Click to deploy more balls', width/2, height-50);
}
for (let j = 0; j <= i; j ++) {
balls[j].move();
balls[j].detectEdge();
balls[j].display();
}
}
function Ball() {
this.pos = createVector(width/2,height/2);
this.speed = 10;
this.vel = p5.Vector.random2D()
this.vel.mult(this.speed);
this.acc = createVector(0,0);
this.r = random(0,255);
this.g = random(0,255);
this.b = random(0,255);
this.radius = 30;
this.move = function() {
this.acc.set(mouseX-this.pos.x,mouseY-this.pos.y);
this.acc.normalize();
this.acc.mult(.2);
this.vel.add(this.acc);
this.vel.limit(this.speed);
this.pos.add(this.vel);
}
this.display = function() {
fill(this.r,this.b,this.g);
noStroke();
circle(this.pos.x,this.pos.y,this.radius);
}
this.detectEdge = function() {
if (this.pos.x >= width-this.radius/2 | this.pos.x <= this.radius/2) {
this.vel.x = -1 * this.vel.x;
} else if (this.pos.y >= height-this.radius/2 | this.pos.y <= this.radius/2) {
this.vel.y = -1 * this.vel.y;
}
}
}
function mouseClicked() {
i++;
balls[i] = new Ball();
}
function keyPressed() {
if (key == ' ') {
init();
}
}