søndag den 16. marts 2008

3D model collision

For a long time, 3D collision has been the biggest problem I have faced in the field of game development. XNA comes with the BoundingBox and BoundingSphere classes that provide a very fast collision solution. However, these classes do not give you very accurate collision detection when applied to 3D models, because they do not check each triangle in the model.

The solution to this problem is writing a CollisionMesh class. This class will be will be used to check Model vs. Model collision, using the model’s triangles.

However, the kind of collision checking is very costly, so it is important to minimize the amount of times we use this method. We can do this by using the BoundingBox class, to check if two models are even close to each other. If model1 and model2’s bounding boxes don’t collide, there is no reason to make the very costly triangle collision test.

Also, it is a good idea to use a low-poly version of you 3D model for collision testing, depending on how accurate your collision needs to be.

For a concrete example of this collision theory, download this sample. Here is a short walkthrough, on how to use the CollisionMesh class:

Creating a CollisionMesh is very simple:

Model MyModel = Content.Load("MyModel");
CollisionMesh collisionMesh;
collisionMesh = CollisionMesh.FromModel(MyModel, Vector3.Zero, Vector3.Zero);
CollisionMesh.RefreshMatrix();
After this, use the following code to check if a movment with the movmentVector, will result in a collision:

Vector3 movmentVector = new Vector3(1,0,0);
bool result = collisionMesh.Move(movmentVector, otherCollisionMesh);
collisionMesh.RefreshMatrix();


Ingen kommentarer: