Only draw visible objects to the camera in 2D

Posted by Deukalion on Game Development See other posts from Game Development or by Deukalion
Published on 2012-11-26T12:17:54Z Indexed on 2012/11/26 17:28 UTC
Read the original article Hit count: 365

Filed under:
|
|
|

I have Map, each map has an array of Ground, each Ground consists of an array of VertexPositionTexture and a texture name reference so it renders a texture at these points (as a shape through triangulation).

Now when I render my map I only want to get a list of all objects that are visible in the camera. (So I won't loop through more than I have to)

Structs:

public struct Map
{
    public Ground[] Ground { get; set; }
}

public struct Ground
{
    public int[] Indexes { get; set; }
    public VertexPositionNormalTexture[] Points { get; set; }

    public Vector3 TopLeft { get; set; }
    public Vector3 TopRight { get; set; }
    public Vector3 BottomLeft { get; set; }
    public Vector3 BottomRight { get; set; }
}

public struct RenderBoundaries<T> 
{ 
    public BoundingBox Box; 
    public T Items; 
} 

when I load a map:

foreach (Ground ground in CurrentMap.Ground) 
{ 
    Boundaries.Add(new RenderBoundaries<Ground>() 
    { 
        Box = BoundingBox.CreateFromPoints(new Vector3[] { ground.TopLeft, ground.TopRight, ground.BottomLeft, ground.BottomRight }), 
        Items = ground 
    }); 
} 

TopLeft, TopRight, BottomLeft, BottomRight are simply the locations of each corner that the shape make. A rectangle.

When I try to loop through only the objects that are visible I do this in my Draw method:

public int Draw(GraphicsDevice device, ICamera camera) 
{ 

BoundingFrustum frustum = new BoundingFrustum(camera.View * camera.Projection); 

// Visible count 
int count = 0; 

EffectTexture.World = camera.World; 
EffectTexture.View = camera.View; 
EffectTexture.Projection = camera.Projection; 

foreach (EffectPass pass in EffectTexture.CurrentTechnique.Passes) 
{ 
    pass.Apply();
    foreach (RenderBoundaries<Ground> render in Boundaries.Where(m => frustum.Contains(m.Box) != ContainmentType.Disjoint)) 
    { 
        // Draw ground 
        count++; 
    } 
}

return count;

}

When I try adding just one ground, then moving the camera so the ground is out of frame it still returns 1 which means it still gets draw even though it's not within the camera's view.

Am I doing something or wrong or can it be because of my Camera?

Any ideas why it doesn't work?

© Game Development or respective owner

Related posts about XNA

Related posts about rendering