QuantumArchi
QuantumArchi

Reputation: 73

bounding box collision xna c#

I am not clear on how to set this up i need boxes rather then spheres in this case because i want to know if a laser hits an enemy ship in my 3D scene. here is my code for the spheres how would i change it to bounding boxes. Because if i were to use spheres for the laser the sphere would be massive and hit a ship even if it was far away from the actual laser. all im asking is how do i go about setting up a bounding box in this fashion.

private bool Cannonfire(Model model1, Vector3 world1, Model model2, Vector3 world2)
        {
            for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
            {
                BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
                sphere1.Center = world1;
                for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
                {        
                    BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
                    sphere2.Center = world2;
                    if (sphere1.Intersects(sphere2))
                        return true;
                }
            }
            return false;
        }   

so how do i this thanks for any help.

Upvotes: 1

Views: 1349

Answers (1)

robasaurus
robasaurus

Reputation: 1032

It sounds like what you need are Rays which can be used to intersect BoundingSpheres and BoundingBoxes in XNA. They are essentially a single straight line or beam which you specify by passing in a start position and direction into the constructor. You can then call the Intersects method and pass in a BoundingBox or Sphere. In your example it would be something like this.

Ray laserBeam = new Ray(startingPosition, direction);
laserBeam.Intersects(shipBoundingSphere);

Note that intersects returns a nullable float value. It will be null if there is no collision or a float value indicating the distance from the Rays startingPosition if there is a collision.

This float value can be used to work out which of your potential targets is closest to ray e.g you loop through your ships and one ship collides with a float value of 3 but the other collides with a float value of 5. You know that the ship with the value 3 is closest to the source of the laser beam so you can ignore the others.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.ray.intersects.aspx

Upvotes: 1

Related Questions