xxxxxxxxxx
46
let ball1;
let ball2;
function setup() {
createCanvas(400, 400);
ball1=new Ball(50,100,30,30,2.5);
ball2=new Ball(100,200,30,30,1);
}
function draw() {
background(0);
ball1.move();
ball1.show();
ball2.move();
ball2.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(){
stroke(255);
strokeWeight(4);
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;
}
}