xxxxxxxxxx
146
// let ballA;
// let ballB;
let balls = [];
let numBalls = 2; // to control number of balls
let minDia = 10; // minimum diameter of balls
let maxDia = 25; // minimum diameter of balls
function setup() {
createCanvas(400, 400);
noStroke();
// for loop to put "numBalls" new ball objects into a list (balls)
for (let i = 0; i < numBalls; i++) {
balls[i] = new Ball(random(width), random(height));
}
// ballA = new Ball(random(width),random(height));
// ballB = new Ball(random(width),random(height))
}
function draw() {
background(50);
// add a ball every frame
balls.push(new Ball(mouseX, mouseY));
// more concise version
for (let i = 0; i < balls.length; i++) {
balls[i].display();
balls[i].move();
//balls[i].bounce();
balls[i].changeColor();
balls[i].checkCanvas();
}
// limit the number of objects
// if(balls.length > 20){
// balls.splice(0,1);
// }
}
// delete things consistently when it is out of the canvas
for (let i = balls.length - 1; i >= 0; i--) {
if (balls[i].isDone == true) {
balls.splice(i, 10);
}
}
// a new ball is added every time mouse is pressed
function mousePressed() {
balls.push(new Ball(mouseX, mouseY));
}
function keyPressed() {
// if "D" or "d" is pressed,
if (key == "d" || key == "D") {
// and if there is at least one object
if (balls.length > 0) {
let index = 0; // the first index = the oldest object
balls.splice(index, 1);
}
}
}
/* depreciated instance creation methods below
// 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].changeColor();
// }
*/
// _______________Class: Ball
class Ball {
// constructor
constructor(x, y) {
this.x = x;
this.y = y;
this.dia = random(minDia, maxDia);
this.xSpd = random(-2, 2);
this.ySpd = random(-2, 2);
this.isDone = false;
}
// ---------- ball class methods
// check the canvas: if ball is out of the canvas...
checkCanvas() {
if (this.x < 0 || this.x > width) {
this.isDone = true;
}
if (this.y < 0 || this.y > height) {
this.isDone = true;
}
}
// displays balls
display() {
ellipse(this.x, this.y, this.dia, this.dia);
}
// move balls
move() {
this.x += this.xSpd;
this.y += this.ySpd;
}
// bounce - change direction when hitting boundaries
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
changeColor() {
// based on walls
if (this.x < 0 || this.x > width) {
fill(random(255), random(255), random(255));
if (this.y < 0 || this.y > height) {
fill(random(255), random(255), random(255));
}
}
}
}