How to perform a rectangle / enemy rectangle collision detection in Space Invaders?

Recently, I posted a question about bullet bullets, which I (with the help of course) managed to find out. I now have a new problem, I can’t detect collision detection between bullets and my enemies. I don’t want to publish all my code at once, so here the list of my classes contains the code in which I will post upon your request:

  • cButton (it's just a play button, no help is needed).
  • Bullets
  • Game1
  • enemies

PS this is just my second post, it’s easy on me;) NOTE: the player only moves from side to side, and the enemies move from top to bottom in the strait line (if that helps at all)

+4
source share
2 answers

Here is a very easy way to do this that I used before. Adjust the rectangle around the bullet:

Rectangle bulletRect = new Rectangle(bulletPosition.X, bulletPosition.Y, bulletText.Width, bulletText.Height); 

The same goes for the enemy:

 Rectangle enemyRect = new Rectangle(enemyPosition.X, enemyPosition.Y, enemyText.Width, enemyText.Height); 

Then when testing collisions you can use:

 if(bulletRect.Intersects(enemyRect)) { //We have a collision } 
+2
source

I assume that you will need to check if the bullet fell into the block that the ship is currently occupying, and if so, destroy it and remove the bullet. This will probably help if you post the appropriate code. :)

0
source

All Articles