Accessing all elements of an array at the same time

Viewed 90

I have two arrays containing a circle object and a wall object..

const allCircles = [circle1, circle2, circle3, circle4]; //
const allFunnelWalls = [funnelBottomLeft, funnelBottomRight, funnelLeft, funnelRight];

I have this function called collide and it takes two arrays as parameters, so far I have it working for one circle and wall because it accesses the elements from both arrays using the same index of "i" How do I create it so that I can access all the elements in the allFunnelWalls array at the same time and test it against each circle? I've tried using the every() method from arrays, nested for loops. I've reached my wits end.. help would be much appreciated

function collide(array, array2){

    for(i = 0; i < array.length; i++){

        // Collision detection algorithm between circles + inner walls
        let collision = lineCircle(array2[i].x, array2[i].y, array2[i].x2, array2[i].y2,
        array[i].x, array[i].y, array[i].radius);

        // Collision detection
        if(collision){
          array[i].colour = "green";
          array[i].xSpeed = 0;
          array[i].ySpeed = 0;
          return true;
        }else{
          array[i].colour = "red";
          return false;
        }
    }
}
1 Answers

You could try a nested map.

function collide(array, array2) {
  let results =  array.map(circle => {
    return array2.map(wall => {
      // Collision detection algorithm between circles + inner walls
      let collision = lineCircle(wall.x, wall.y, wall.x2, wall.y2,
         circle.x, circle.y, circle.radius);

    // Collision detection
    if(collision) {
        circle.colour = "green";
        circle.xSpeed = 0;
        circle.ySpeed = 0;
        return circle;
    }else{
        circle.colour = "red";
        return circle;
    }
    })
  })
  /* if you want to examine the results, you can do so here
  [
    { colour: 'green', xSpeed: 0, ySpeed: 0 },
    { colour: 'green', xSpeed: 0, ySpeed: 0 },
    { colour: 'green', xSpeed: 0, ySpeed: 0 }
  ],
  [
    { colour: 'red'}
  ],
  */

  return results.any(result => result.colour === "green");
}
Related