Saturday, July 6, 2013

XNA 3D Simple Collision Detection with BoundingSphere



First declare a Model for the 3ds max object you want to use..

Model 3dsMaxModel, 3dsMaxHouseModel;
Vector3 ModelPosition, housePosition;


In your load content..

//SET THE MODEL INTO THE VARIABLES
3dsMaxModel = Content.Load("ModelName");
3dsMaxHouseModel= Content.Load("ModelName");
//SET THE POSITION
ModelPosition = Vector3.Zero;
housePosition = new Vector3(10,1,10);


Create a new method for checking the collision
The method will use 4 variables, it is pretty much self explanatory.
public void CollisionTest(Model _model1, Model _model2, Vector3 _model1Position, Vector3 _model2Position){
//Create a new bounding sphere for the first model..

BoundingSphere obj = _model1.Meshes[0].BoundingSphere; // Get the bounding sphere for the mesh
obj.Center = _model1Position; //SETS the center of the bounding sphere

//For the second object..
BoundingSphere obj2 = _model2.Meshes[0].BoundingSphere;
obj2.Center = _model2Position;

if(obj.Intersects(obj2)){
//DO SOMETHING, This is where we are gonna code what happens to the model when it intersects with another model
}
}


And be sure to put use the CollisionTest in your update method..

CollisionTest(3dsMaxModel,3dsMaxHouseModel,ModelPosition,housePosition);