I am building a ball physics simulator in Javascript. I understand how to detect collisions for individually created objects, but struggle when the objects are constructed using ES6 classes. Here is the code I have so far.
Ball Constructor
const Ball = class {
constructor(x, y, dx, dy) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
}
checkForWall() {
if (this.x + ballRadius < ballRadius) {
this.dx = -this.dx;
}
if (this.y + ballRadius < ballRadius) {
this.dy = -this.dy;
}
if (this.x + ballRadius > canvas.width) {
this.dx = -this.dx;
}
if (this.y + ballRadius > canvas.height) {
this.dy = -this.dy;
}
}
moveBall() {
this.x += this.dx;
this.y += this.dy;
}
};
Ball Drawing Function on Canvas
const drawBalls = function (x, y) {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = `green`;
ctx.fill();
ctx.closePath();
};
Drawing Function on canvas with interval timer
const draw = function () {
ctx.clearRect(0, 0, canvas.width, canvas.clientHeight);
drawBalls(ballOne.x, ballOne.y);
drawBalls(ballTwo.x, ballTwo.y);
ballTwo.moveBall();
ballTwo.checkForWall();
ballOne.moveBall();
ballOne.checkForWall();
}
let interval = setInterval(draw, 10);
Is there a way to implement code in the above class to check whether or not balls constructed from this class have collided with other balls constructed from the same class in the same way that I am able to check for collision with the canvas walls? Do I need to create a parent class and a child class?