Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
How to check for collision on canvas for objects created from the same class?

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?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda