Sunday, January 16, 2011

XNA Game Development Tips and Tricks 6: 2D Collision Detection make easy for player

We will see how we can do the collision detection and how we can make it a bit easier for the player. Collision detection is one of the most discussed part of game development. Now lets say we have two sprites moving in our game and we want to detect whenever they collide with each other.

What we have here is Sprite’s X and Y Coordinates and its Width and Height. So we will be taking both sprite’s X and Y coordinates and Width and Height and figure out whether both intersects with each other or not. Let’s take a look at the following code:

public bool CheckCollision(Rectangle sourceRect, Rectangle destRect)
{
      return sourceRect.Intersects(destRect);
}

Above code does a perfect collision detection, but there is a little problem with player. We should be giving a little freedom to player so that game does not become very difficult for player. In order to do that we are going to Inflate the Sprite.. dont worry this inflation is only logical and will not be displayed to user.

public bool CheckCollision(Rectangle sourceRect, Rectangle destRect)

      sourceRect.Inflate(5, 5);
      return sourceRect.Intersects(destRect);
}

By Inflating we are inflating one of the Sprite by 5x5. We can Inflate both Sprites as well. Depending on how easy you would want game to be you can decide how much sprite you would like to Inflate.

No comments:

Post a Comment