xxxxxxxxxx
49
let balls=[];
function setup() {
createCanvas(400, 400);
for (let i=0;i<20;i++){
let x=random(100);
let y=random(100);
let r=random(20,30);
let xspeed=random(1,3)
let yspeed=random(5,10)
balls[i]=new Ball(x,y,r,xspeed,yspeed);
}
}
function draw() {
background(220);
for (let i=0;i<balls.length;i++){
balls[i].move();
balls[i].show();
}
}
class Ball{
constructor(x,y,r,xspeed,yspeed){
this.x=x;
this.y=y;
this.r=r;
this.xspeed=xspeed;
this.yspeed=yspeed;
}
move(){
this.x += this.xspeed;
this.y += this.yspeed;
this.xspeed = this.bounce(this.x, 0, width,this.xspeed);
this.yspeed = this.bounce(this.y, 0, height, this.yspeed);
}
show(){
fill("red");
ellipse(this.x,this.y,this.r);
}
bounce(pos, low, high, speed){
if (pos< low || pos> high){
return speed*= -1;
}else return speed;
}
}