Search code examples
javascriptarraysloopscollision

Objects from same array using for loop with j = i + 1


I have a loop to check collision between objects in my game, all the objects are collected in the same Array. I use a code like this to match every object with eachother:

for (var i = 0; i < objs.length; i++) {
    for (var j = i + 1; j < objs.length; j++) {
        collision(objs[i], objs[j]);
    }
}

Now this does not seem to actually perform all collisions with eachother, I've noticed that it skips some too..

Then I came up with this solution:

for (var i = 0; i < objs.length; i++) {
    for (var j = 0; j < objs.length; j++) {
        if (j != i) {
            collision(objs[i], objs[j]);
        }
    }
}

This solution seem to not have any problems, but I wonder if there is any kinda way to not have to use the if (j != i) statement, or is there maybe a totally different solution?


Solution

  • Soo, who's correct eh..?

    It depends on the definition of collision in your game.

    If collision is a symmetric function (i.e. A collides with B if, and only if, B collides with A), then use:

    for (var i = 0; i < objs.length; i++) {
        for (var j = i + 1; j < objs.length; j++) {
            collision(objs[i], objs[j]);
        }
    }
    

    because there's no need to check (B,A) if you checked (A,B) before.

    But if it is possible to make A collide with B without making B collide with A, or vice versa, then you must check all possible different pairs, so use

    for (var i = 0; i < objs.length; i++) {
        for (var j = 0; j < objs.length; j++) {
            if (j != i) {
                collision(objs[i], objs[j]);
            }
        }
    }