Error when splice() is called

Hello everybody!

We have a problem with the splice() syntax.

Our program works by generating a lot of bubbles, and the bubbles then start to consume each other and will then grow bigger.

The problem occurs randomly and poses the following error.

You can find the code here

Thank you in advance :raised_hands:

@shiffman plz help :pray:

Hi! Welcome to the forum!

I know you need help but please be patient :sweat_smile: In fact Dan explains in some of his videos about the splice trick.

1 Like

You’re not checking very clearly to make sure that you’re always accessing a Bubble in the bubbles that still exists.

I suspect that you are trying to remove the smallest of the two bubbles when two bubbles collide. But what if , for example, you have three bubbles in the array, and the smallest one is the second one, and it collides with the third one? You would remove the second one from the array, and then try to increase the size of the third one… BUT THERE ISN’T A THIRD ONE ANY MORE! You JUST shrunk the array when you called splice! And that’s why you get an error.

Instead, I would simplify the logic. First, change it so that when you draw a bubble, if that bubble has a size of 0, just don’t draw it. Then, when checking for colliding bubbles, increase the size of one, and set the other to have a size of 0. Also add a check to make sure you are not trying to check for collisions of bubbles that have a size of zero. Finally, after all the collisions are done, loop over the array of bubbles BACKWARDS, and remove any (using splice) that have a size of zero.

// ---
void draw(){
  if( this.r == 0 ){ return; }
  // ...
}
// ---
for( i ){
  for( j ){
    if( i != j && bubbles[i].r != 0 && bubbles[j] != 0 ){
      if( collides(i, j ) ){
        if ( bubbles[i].r < bubbles[j].r ){
          bubbles[i].r = 0;
          bubbles[j].r += 10;
        } else {
          // The other way.
}}}}}}}}} // Or whatever.
for( i = bubbles.length - 1; i >= 0; i-- ){  // Loop backwards to not goof up indexes while removing things.
  if( bubbles[i].r == 0 ){
    bubbles.splice( i , 1 );
  }
}

Also, make sure that you’re using proper constants in your bubble classes’s intersect() function. Consider this line:

		if (d < bubbles[0].r + bubbles[1].r) {

This will break if you only have one bubble!