Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!