xxxxxxxxxx
55
var balls = [];
var button;
function setup() {
createCanvas(500, 300);
for (let i = 0; i < 2; i++) {
balls[i] = new Ball(100, 200);
}
button = createButton("Press to try!");
button.mousePressed(hi);
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
this.xs = 3;
this.ys = -4;
this.col = map(this.x, 0, 500, 0, 255);
}
move() {
this.x = this.x + this.xs;
this.y = this.y + this.ys;
}
show() {
fill(0, this.col, this.col-10);
noStroke();
ellipse(this.x, this.y, 24, 24);
}
bon() {
if (this.x > width || this.x < 0) {
this.xs = this.xs * -1;
}
if (this.y > height || this.y < 0) {
this.ys = this.ys * -1;
}
}
}
function hi() {
balls.push(new Ball(random(width), random(height)));
}
function draw() {
background(255, 255, 0, 50);
for (var i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].bon();
balls[i].show();
}
}