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

152
Vistas
Js canvas; how to check for collision between two circles

i have and object with X;Y coordinates of a green circle, radius const =5. name "Food". 50 objects with random placement around the canvas.

I have and object with X;Y coordinates of a red circle, radius const =8. name "player".

I have X;Y array of coordinates going x,y 50 times (100 cords), name "allFood". with all of the "food" objects

i need to check for collision between food and player on canvas and add scoreboard. I made a workable piece of code:

    for (let i = 0; i < 100; i=i+2){
        if ((player.x == allFood[i]) && player.y ==(allFood[i+1])){
            scoreboard=scoreboard+1
            score.innerHTML = scoreboard
        }
    }

But it checks only if player centre of circle and food centre of circle are pinpoint accurate on the same pixel, which is very annoying. Could anyone help improve the code so its works when both radiuses collide? i dont know any way except 160 ifs checking each pixel..

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If the center of player circle is less than (radius 5 + radius 8) = 13 units away from the center of a food circle, they are colliding. Use Pythagoras to calculate the distance.

for (let i = 0; i < 100; i=i+2){
  let distance = Math.sqrt(Math.pow(player.x - allFood[i], 2) + Math.pow(player.y - allFood[i + 1], 2))
  if (distance <= 13) {
      scoreboard=scoreboard+1
      score.innerHTML = scoreboard
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
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