xxxxxxxxxx
67
let balls = [];
function setup() {
createCanvas(400, 400);
// ball1=new Ball(width/2,height/2);
for (let i = 0; i < 20; i++) {
balls[i] = new Ball(random(width), random(height), random(100))
}
}
function draw() {
background(0);
for (let i = 0; i < balls.length; i++) {
balls[i].display();
balls[i].bounce();
for (let j = i+1; j < balls.length; j++) {
if (balls[i].collide(balls[j])) {
// balls[i].changeCol();
// balls[j].changeCol();
balls.splice(i,1);
balls.splice(j,1);
}
}
}
}
class Ball {
constructor(tempX, tempY, tempD = 10, tempXvel = 1, tempYvel = 2, tempCol = color(255, 255, 255),tempColChanged=false) {
this.x = tempX;
this.y = tempY;
this.d = tempD;
this.xVel = tempXvel;
this.yVel = tempYvel;
this.col = tempCol;
this.colChanged=tempColChanged;
}
display() {
fill(this.col);
noStroke();
circle(this.x, this.y, this.d);
}
bounce() {
this.x += this.xVel;
this.y += this.yVel;
if (this.x < this.d / 2 || this.x > width - this.d / 2) {
this.xVel *= -1;
}
if (this.y < this.d / 2 || this.y > height - this.d / 2) {
this.yVel *= -1;
}
}
collide(other){
let distance=dist(this.x,this.y,other.x,other.y);
return (distance<this.d);
}
changeCol(){
if(this.ColChanged){
this.col=color("red");
}else{
this.col=color("white");
}
this.colChanged=!this.colChanged;
}
}