xxxxxxxxxx
93
/*
*** BOUNCING BALL (ES6) ***
Classes in ES6 with The Coding Train ˜ https://thecodingtrain.com/
The variable `interval` is for helping with randomness of the bouncing pattern.
Sketch made by Leonardo M. Louzas ( https://github.com/leonardomlouzas ) | 20/aug/24
*/
class Ball {
constructor(size, interval, HVelocity, VVelocity = HVelocity) {
this.x = random(0, width);
this.y = random(0, height);
this.r = random(0, 255);
this.g = random(0, 255);
this.b = random(0, 255);
this.HVelocity = HVelocity;
this.VVelocity = VVelocity;
this.size = size;
this.interval = interval;
}
// Display the ball
show() {
stroke(255);
strokeWeight(4);
fill(this.r, this.g, this.b);
ellipse(this.x, this.y, this.size, this.size);
}
// Move the ball
move() {
this.x += this.HVelocity;
this.y += this.VVelocity;
}
// randomize the ball color
randomize() {
this.r = random(0, 255);
this.g = random(0, 255);
this.b = random(0, 255);
}
// Change ball move direction.
// The isH parameter is for checking if the collision was on the horizonal edge or not.
collide(isH) {
if (isH) {
if (ball.x > width) {
this.x = width;
} else {
this.x = 0;
}
this.y = random(this.y - this.interval, this.y + this.interval);
this.HVelocity *= -1;
} else {
if (this.y > height) {
this.y = height;
} else {
this.y = 0;
}
this.x = random(this.x - this.interval, this.x + this.interval);
this.VVelocity *= -1;
}
this.randomize();
}
}
let ball;
function setup() {
createCanvas(600, 400);
// Creates a ball instance. (size, interval, horizontal velocity, [vertical velocity]).
// If inserted a single velocity value, the vertical velocity will be the same as the horizontal velocity.
ball = new Ball(100, 10, 10);
}
function draw() {
// display and move the ball
ball.show();
ball.move();
// Check for horizontal collision and run the collide function with isH = true.
if (ball.x > width || ball.x < 0) {
ball.collide(true);
}
// Check for Vertical collision and run the collide function with isH = false.
if (ball.y > height || ball.y < 0) {
ball.collide(false);
}
}