Google+

Friday, September 2, 2011

Let's Make A Game! Episode 15: When Enemies Collide!

Collision detection in 2D games is handled surprisingly easily in XNA.

A brief explanation of what collision detection is: Games are built on things colliding. For example, it's important to know that Mario has touched a Goomba and also from which direction. It's important to know that Mario has hit a brick from below. It's important to know when he's free-falling. That's what we call collision detection: Making sure that two objects, be they friend or foe, are or aren't touching.
In all the programming I've done, I've had to do those calculations myself. I've had to tell the game, "Hey, look. My character is X pixels wide. I need you to measure from the bottom left corner of the character (or whatever), add X pixels, and then tell me if there's anything touching my character." It's not unwieldy, but not a lot of fun either.

In XNA, you're working with rectangles. Here's the code:
// Do the collision between the player and the enemies
for (int i = 0; i
{
rectangle2 = new Rectangle((int)enemies[i].Position.X,
(int)enemies[i].Position.Y,
enemies[i].Width,
enemies[i].Height);

// Determine if the two objects collided with each
// other
if(rectangle1.Intersects(rectangle2))
{
// Subtract the health from the player based on
// the enemy damage
player.Health -= enemies[i].Damage;

// Since the enemy collided with the player
// destroy it
enemies[i].Health = 0;

// If the player health is less than zero we died
if (player.Health <= 0)
player.Active = false;
}

}

BOOM. Rectangle1 gets assigned to the player. Rectangle2 is assigned to each enemy in turn, and the game is basically asking in turn, "Hey, Enemy 1, are you and the player intersecting? No? Well, what about you, Enemy 2? No? OK. Enemy 3? Yes? All right, now we'll adjust the game accordingly."

It's not a perfect system, because if your character isn't exactly a rectangle, it may end up in some people saying, "Hey, that didn't really hit me!" Still, it's a heck of a lot easier than doing all the calculations ourself. Thanks, XNA!