Testing for Collisions
Demonstrates how to use the BoundingSphere class to check whether two models are colliding.
Tip
This technique is implemented in the FuelCell game, a game developed by following a series of focused articles that discuss basic 3D game development. For more information, see FuelCell: "Ships" Passing in the Night.
The Complete Sample
The code in the topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Download CollisionBetweenSpheres.
Detecting Whether Two Models Collide
To check whether two objects are colliding
Track the position of a model as it moves about the game world.
struct WorldObject { public Vector3 position; public Vector3 velocity; public Model model; public Texture2D texture2D; public Vector3 lastPosition; public void MoveForward() { lastPosition = position; position += velocity; } public void Backup() { position -= velocity; } public void ReverseVelocity() { velocity.X = -velocity.X; } }
Make a nested loop with the first model's meshes as the outer loop and the second model's meshes as the inner loop.
Inside the loop, follow these steps.
Get the bounding sphere for the current mesh of the first model and the current mesh of the second model.
Offset the bounding spheres by the current positions of the models.
Call the BoundingSphere.Intersects method to check the pairs of bounding spheres for collision.
If the method returns true, the objects are colliding.
If the models are colliding, break out of the loop.
static void CheckForCollisions(ref WorldObject c1, ref WorldObject c2) { for (int i = 0; i < c1.model.Meshes.Count; i++) { // Check whether the bounding boxes of the two cubes intersect. BoundingSphere c1BoundingSphere = c1.model.Meshes[i].BoundingSphere; c1BoundingSphere.Center += c1.position; for (int j = 0; j < c2.model.Meshes.Count; j++) { BoundingSphere c2BoundingSphere = c2.model.Meshes[j].BoundingSphere; c2BoundingSphere.Center += c2.position; if (c1BoundingSphere.Intersects(c2BoundingSphere)) { c2.ReverseVelocity(); c1.Backup(); c1.ReverseVelocity(); return; } } } }
Note
For an example of determining a particle's path after it hits a surface, see Vector3.Reflect.
See Also
Tasks
Rotating and Moving the Camera
Concepts
Bounding Volumes and Collisions
Collision Content Catalog at App Hub Online