Search code examples
algorithmxna2dcollision-detection

Space Invaders collision detection. 1 bullet check all invaders?


I have developed a grid of invaders that I can shoot a bullet towards.

The only solution I know of for collision detection is using two Rectangles and the Intersects method.

Now, it is my feeling that it is not efficient to compare each bullet to every invader on the screen.

Is there another solution I can use here that is more intelligent and only compares some invaders.

I propose to use a flag for the X axis, that is populated with the X position of the bullet when fired. The invader sprites will have access to this flag and will only run the intersects method if the invader sprite is on that X position (+/- a few px). This would greatly reduce the number of comparisons.

Any ideas? Thanks.


Solution

  • You're correct, there is something you can do that is potentially more efficient. By dividing space into coarse-grain sections and seeing which section the bullet is in, you can prune off the invaders in other sections. You can go one step further and have multiple layers of "coarseness" or resolution.

    At the end of this train of thought is a data structure called the quad tree. It is a natural and efficient way to do collision detection in two dimensions.