简体   繁体   中英

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?

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]

If you can use ES2015, Set allows only unique members of the set. From MDN:

The Set object lets you store unique values of any type, whether primitive values or object references.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

[...new Set(objects)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM