Monday 2 January 2012

Collision detection the easy way

So the easiest way to do collision detection in XNA is to have a bounding box around the 2D Sprite, basically a rectangle.

Then if two sprites collide, then their bounding boxes intersect and you can check for this with the standard Intersect method in XNA.

Great, so a 2D concept is easy to move to a 3D world, just add the Z axis.

It would seem XNA 4.0 doesn't support 3D bounding boxes any more and just has bounding spheres.

Same concept but rather than having a cube to check for intersection you have a sphere that surrounds the model (or sub elements of the model).

So far so good, all I need to do is add a collision routine for checking if the player sphere has intersected with the building block spheres.

If a collision occurs then I just set the player position back to the position it was before the player moved (I also reverse the velocity of the object)

So running the game and yes collision works, somewhat.

The UFO seems to heavily clip the building blocks and it will disappear inside a building until the collision occurs.

Then when it does occur, it seems the player UFO bounces rapidly against the colliding object.

Firstly, why do I get this clipping effect? Well it's because my objects are not best suited to bounding spheres as they are more cube like in shape so the spheres will not surround the model in the desired way.

Bounding boxes would be much better. But XNA 4.0 doesn't have them any more.

Looking on google, it seems like someone has added them back by extending the content pipeline.(link)

Basically they have built a custom content processor for 3D models that adds bounding boxes for all objects in the model mesh.

That's what I need.

No comments:

Post a Comment