Question

I am writting a simple metaballs implementation in JS. I have an array of the metaballs and i iterate through all of them every frame, and for each one I check the distance to every other metaball and if they are close enough I need to merge them.

This is how I guess it could look, but I don't know how to properly remove the element from array and not break the loops.

for(var i = 0; i < points.length; i++) {
    for(var j = 0; j < points.length ; j++) {
        if(i != j) {
            if(distance < 10) {
                //remove one of the points using splice
            }
        }
    }
}

Thanks for help.

Était-ce utile?

La solution

First, start your inner loop at i + 1. You've already compared elements up to i, so there's no need to repeat, right? That let's you get rid of your if statement as well.

Then, when you splice, decrement j so as to not skip the next element.

for(var i = 0; i < points.length; i++) {
    for(var j = i + 1; j < points.length ; j++) {
        if (distance(i, j) < 10) {
            points.splice(j--, 1);
        }
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top