Collision Detection

After much tweaking and poking of the collision detection code, the pipeline code, and some impressive XML files, I can say this weekend’s quest to implement some basic collision test was quite successful indeed.  The new code takes in a couple of sprites and spits back out both whether or not they bumped into each other and if so, how it happened.  It detects first whether or not the sprites overlap on a basic level usually referred to as “Bounding Box.”  That is, do the rectangles that the sprites live in overlap each other at all?  If they don’t, well, then there is no point doing more work.  This test is brutally simple and fast and can almost instantly get you an answer if you don’t overly care about silly things like accuracy or have the amazing opportunity to check on sprites that completely fill their bounding boxes.

Once you know the pictures actually overlap, the next goal is to determine if they actually do.  I know that sounds weird, but a spaceship that lives in a box would have big sections of the box that aren’t full of spaceship, well, unless it was a really blocky looking spaceship I guess.  When a missle enters the bounding box in a section not full of spaceship but counts as a hit anyway, players get annoyed.  In a tricky process you can look deeper at the actual pixels of the spaceship and missle to see if they overlap.  This process takes a good deal of extra work to accomplish and can be a pain to make it go quickly.  That is where the pipeline comes in.

In the XNA content pipeline you have a unique opportunity to pre-calculate things to get them ready for use in your game.  By moving the heavier parts of the pixel level detection down into the pipeline you can take that load out of the game, which naturally makes it run faster.  Add to that careful additional checks and simplified math and logic to optimize what has to be done in realtime and you can end up with a pretty slick little piece of code indeed.

Leave a Reply

You must be logged in to post a comment.