# Multiple Collision Detection in Invaders Game

• January 25th, 2013, 07:01 PM
jm24
Multiple Collision Detection in Invaders Game
Ok so I'm not getting any errors with this code or anything, but there is a small problem. Basically I'm making an invaders game and to hold the different invaders I have an 2D array called invaders (all of the Invader objects extend Rectangle2D.Double). The laser object is basically just another Rectangle2D.Double that is fired by the player at the invaders. I have a timer firing every 85 milliseconds, and every time it fires it does the following check to see if there is a collision between the laser and any of the invaders; if there is it removes the laser and replaces the hit invader with a blank one. The problem is that the way I'm currently checking them causes the program to miss the collisions of some of the invaders because it goes through the invaders 2D array row by row checking for collisions. Can anyone tell me a more efficient way of checking the collisions all at the same time (or at least quicker) than going through row by row?

Here is the collision check:
Code :

```if(laser != null && laser.hasFired) for(int row = 0;row < 5;row++) for(int col = 0;col < 11;col++) if(laser.getBounds2D().intersects(invaders[row][col].getBounds2D()) && invaders[row][col].alive){ laser.setFired(false); invaders[row][col].isAlive(false); score += 10; for(int x = 0;x < 5;x++) for(int y = 0;y < 11;y++) invaders[x][y].increaseSpeed(); }```
• January 25th, 2013, 07:07 PM
Norm
Re: Multiple Collision Detection in Invaders Game
Quote:

miss the collisions of some of the invaders because it goes through the invaders 2D array row by row checking for collisions.
Not sure how it misses collisions. If it tests all the contents of the array, how does it miss any?
• January 25th, 2013, 07:19 PM
jm24
Re: Multiple Collision Detection in Invaders Game
Quote:

Originally Posted by Norm
Not sure how it misses collisions. If it tests all the contents of the array, how does it miss any?

I'm honestly not completely sure. I think it has something to do with the timing of the laser moving upwards and which collision it happens to be checking at that moment. It does register some collisions, just not all of them.

--- Update ---

The fact that the laser is also on a separate timer for movement with a shorter firing interval might have something to do with it. Could that be the problem?
• January 25th, 2013, 07:26 PM
Norm
Re: Multiple Collision Detection in Invaders Game
Are things moving while the test is made for collisions?

Time how long it takes to check all the elements in the array? Is that too long for the animation?
• January 25th, 2013, 07:26 PM
jm24
Re: Multiple Collision Detection in Invaders Game
Actually that was the problem haha. I messed with the timer a little bit and got it to work. Thanks anyway though :)