Search code examples
javascriptobjectcollision-detectioncollision

Checking Collision Lots of Objects JS


I've been working with an array allShapes. This array consists of objects with the same kinds of properties, like each object has a .x value, and a .y value.

Each shape has a "radius", so the detection can be easily done. For each object, the radius is exactly the same. It equals 10.

How can I effeciently make a function that checks if one shape is colliding with another? Thanks in advance!

var allShapes = [{70,30},{40,90},{287,245}];
// allShapes[0].x = 70
// For each object, there is a .x and .y value

Solution

  • var allShapes = [{70,30},{40,90},{287,245}];
    
    for(let i = 0; i < allShapes.length - 1; i++) {
      for(let j = i + 1; j < allShapes.length; j++) {
        //check if allShapes[i] and allShapes[j] are colliding
      }
    }
    

    Breakdown of detection:

    - allShapes[i] = {70,30}
      - allShapes[j] = {40,90} => check collision
      - allShapes[j] = {287,245} => check collision
    - allShapes[i] = {40,90}
      - allShapes[j] = {287,245} => check collision