Jack Minney
Jack Minney

Reputation: 61

How do I perform bullet/enemy rectangle collision detection in a Space Invaders-like game?

I have recently posted a question regarding firing bullets which I (with help of course) managed to figure out. I now have a new problem, I am unable to figure out collision detection between bullets and my enemies. I don't wan't to post all my code at once so here's the list of my classes the code in which I will post at your request:

P.S. this is only my second post, go easy on me ;) NOTE: the player only moves side to side and the enemies move from top to bottom in a strait line (if that helps at all)

Upvotes: 4

Views: 2256

Answers (2)

dtsg
dtsg

Reputation: 4459

Here's a very simple way of doing it that I've used before. Set up a rectangle around the bullet:

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

The same for an 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
}

Upvotes: 2

Shawn
Shawn

Reputation: 2366

I'm assuming you'll have to check if the bullet entered a block that a ship is currently occupying, and if so destroy it and remove the bullet. It would probably help if you posted the relevant code. :)

Upvotes: 0

Related Questions