Rotated Rectangle Collision

This sample demonstrates how to implement collisions for rotated rectangles using the Seperating Axis Theorem.

Rotated Rectangle Collisions

Using the Seperating Axis Theorem to implement collision dection for 2D rectangles

 

The XNA framework has an object called “Rectangle”. These objects work great for tracking collision areas for your sprite. They have a built in Intersects() method that is part of the Rectangle object that will allow you to check if one Rectangle is currently colliding with another Rectangle. For most introductory games this may be all you need.

One day however, you may do something out of the ordinary. Instead of moving your sprite in straight lines, you decide to rotate it! You can draw the sprite on the screen rotated fairly easily. The Draw() method of the SpriteBatch has a parameter for that and does it for you. But no matter how hard you look, you can’t find a way to rotate your corresponding collision Rectangle that you have in code. It’s not part of the framework.

That is why I wrote this sample. I wanted to know just how in the world I could detect collisions between rotated rectangles and I thought you might want to know too.

The sample uses the Separating Axis Theorem to determine collisions and it seems to work fairly well. You may find when examining the sample that there are inefficiencies (you may find that it works great for your game and never notice any inefficiencies at all too!). When it came to creating the sample, I tended to go for readability instead of attempting optimize.

I hope this sample helps the XNA community and I’d love to hear any feedback you might have!

Technorati Tags: