Culling - is object inside Camera View

From XNAWiki
Jump to: navigation, search

Culling is a way to speed up rendering by not rendering the objects that are outside the camera view, and can't be seen anyway.

Using XNA build in Frustum Culling Function
This example is using the most basic culling. The are other, more advanced ways to do this.

//Inside your camera class
 
Matrix view;
Matrix projection;
/// The bounding frustum of the camera.
public BoundingFrustum Frustum;
 
public void Update()
{
    // Computes the bounding frustum.
    Frustum = new BoundingFrustum(view * projection);
// note that computing a new frustum every frame will make
// garbage.  You can create the frustum once during initialization
// and then just update the matrix with:
// Frustum.Matrix = view*projection;
}
//Inside your draw method
ContainmentType currentContainmentType = ContainmentType.Disjoint;
 
//For each gameobject
//(If you have more than one mesh in the model, this wont work. Use BoundingSphere.CreateMerged() to add them together)
BoundingSphere meshBoundingSphere = Model.Meshes[0].BoundingSphere; 
currentContainmentType = defaultCamera.Frustum.Contains(meshBoundingSphere);
if (currentContainmentType != ContainmentType.Disjoint)
{
   //Draw gameobject
}
//Loop