xxxxxxxxxx
62
class BouncingBall {
constructor() {
// creates instruction within the lass
this.xPos = random(100, 300);
this.yPos = random(100, 300);
this.xSpeed = 4;
this.ySpeed = 7;
// you must add this bcs they are private tp the class
}
move() {
// move the ball
this.xPos += this.xSpeed;
this.yPos += this.ySpeed;
}
checkForCollisions() {
// check first for left and right wall
if (this.xPos <= 15 || this.xPos >= width - 15) {
this.xSpeed = -this.xSpeed;
}
// do the same for the ceiling and the floor
if (this.yPos <= 15 || this.yPos >= height - 15) {
this.ySpeed = -this.ySpeed;
}
}
draw() {
circle(this.xPos, this.yPos, 30);
// end of the class definition we still have not used it
}}
let myBouncingBall;
let otherBouncingBall;
function setup() {
createCanvas(400, 400);
myBouncingBall = new BouncingBall();
otherBouncingBall = new BouncingBall();
// making the logic within the class
}
// here we call the class and add new to it - what to do
function draw() {
background(240);
myBouncingBall.move();
myBouncingBall.checkForCollisions();
myBouncingBall.draw();
// the last one is calling the class then calling the class within it
// using the same class for multiple balls easier to use insted of recreating the samle code
otherBouncingBall.move();
otherBouncingBall.checkForCollisions();
otherBouncingBall.draw();
// here you are using the class to do smth
}
// classes are helpfull when you want to do many objects so you make many balls with one class rather than copy pasting thesame logic