To check collision with a grid of tiles

I’ve been making a game that is based off of Atari Breakout. I came across the problem of checking collision between a huge amount of objects. so I had to make an algorithm to help.

I had each column assigned to a different group inside a list.
I had all the sprites inside a main group.

I checked the collision for the main group, then if it did collide, I went through all of the columns and checked collision with those, then I called break; to avoid glitches. Next, I went through all the sprites in the group that I just found, and broke out once it found it. then, I did some maths to add to the score and other stuff, but it returned an XY value in the grid i checked, and i used that to remove the sprite.

heres some of my code:

if (ball.isTouching(blocks)) { //detecting collision between ball and blocks
  for (var i = 0; i < 8; i++) { //panning through columns searching for first one ball is touching, 8 columns
    if (ball.isTouching(blocksX[i])) {
      x = i;
      break;
    }
  }
  for (var i = 0; i < 6; i++) { //panning through the rows, 6 rows
    if (ball.isTouching(blocksX[x].get(i))) {
      y = i;
      break;
    }
  }
  return blocksXY[y][x];
}

This can be done with any grid of tiles, just change the X and Y in the for loops accordingly… If you need to, fell free to adapt my code to use it in your games.

here’s a link to the game, so you can see it in action:

2 Likes

Too cool! Thanks so much for sharing!

1 Like