xxxxxxxxxx
111
// let ballA;
// let ballB;
let balls = [];
let numBalls = 5; // to control number of balls
function setup() {
createCanvas(600, 600);
noStroke();
// for loop to put 10 new ball objects into a list (balls)
for(let i =0;i<numBalls;i++){
balls[i] = new Ball(random(width),random(height));
//
for (let i = 0; i < 2; i++) {
balls[i] = new Ball(random(width), random(height));
}
// add new ball manually
balls.push(new Ball(width/2,height/2));
}
// ballA = new Ball(random(width),random(height));
// ballB = new Ball(random(width),random(height))
}
function draw() {
background(50);
// ballA.display();
// ballA.move();
// ballA.bounce();
// ballA.changeColor();
// ballB.display();
// ballB.move();
// ballB.bounce();
// ballB.changeColor();
// another for loop to display each ball in balls
for(let i=0;i<balls.length;i++){
balls[i].display();
}
for(let i=0;i<balls.length;i++){
balls[i].move();
}
for(let i=0;i<balls.length;i++){
balls[i].bounce();
}
for(let i=0;i<balls.length;i++){
balls[i].changeAspect();
}
}
// add new balls by mousepress
function mousePressed(){
balls.push(new Ball(mouseX, mouseY));
}
// _______________Class: Ball
class Ball {
// constructor
constructor(x, y) {
this.x = x;
this.y = y;
this.diax = random(10, 20);
this.diay = random(10, 20);
this.xSpd = random(-2, 4);
this.ySpd = random(-2, 4);
}
// ---------- ball class methods
// move
move() {
this.x += this.xSpd;
this.y += this.ySpd;
}
// bounce
bounce() {
if (this.x < 0 || this.x > width) {
this.xSpd = this.xSpd * -1;
}
if (this.y < 0 || this.y > width) {
this.ySpd = this.ySpd * -1;
}
}
// change color
changeAspect() {
if (this.x < 0 || this.x > width) {
this.diax += random(-30,30);
fill(random(255), random(255), random(255));
if (this.y <= 0 || this.y >= height) {
this.diay += random(-30, 30);
fill(random(255), random(255), random(255));
}
}
}
// displays balls
display() {
ellipse(this.x, this.y, this.diax, this.diay);
}
}