ruttydm ruttydm - 1 month ago 8
Javascript Question

Iterating array over array without duplicates

I am writing a simple game with a simple collision detection system.

I currently have this code for iterating the array over the same array so i can check if the objects are close to each other and if they will collide:



var objects = []; //assume this is not empty


for(i=0;i<objects.length;i++){
for(a=0;a<objects.length;a++){
if(a != i){
//collision handling
}
}
}





But the main problem with this code is that I have duplicates.
For example I check i and a but somewhere later i check a and i with the same values.

I tried using an array that saves which objects are checked with which objects but it gives me a big fps drop.

What is the best method to do this?

Answer

Start your second for loop in the current place of the first for loop:

for(i=0;i<objects.length;i++){
    for(a=i+1;a<objects.length;a++){
      //collision handling
    }
}

This way you check every item in your array only against the items ahead of the current item.

lets check your original code:

objects = ['a', 'b', 'c']
for(i=0;i<objects.length;i++){
  for(a=0;a<objects.length;a++){
    if(a != i){
      console.log("Checking "+ objects[i]+ "vs. "+objects[a]);
    }
  }
}

Now, lets check my example:

objects = ['a', 'b', 'c']
for(i=0;i<objects.length;i++){
  for(a=i+1;a<objects.length;a++){
    console.log("Checking "+ objects[i]+ "vs. "+objects[a]);
  }
}

The general idea is to compare every item only to the items that are followed in the array:

[a, b, c, d]
 a => vs b, c, d    ar[0] vs ar[1], ar[2], ar[3]
    b => vs c, d    ar[1] vs        ar[2], ar[3]
       c => vs d    ar[2] vs               ar[3]