Simple Grid in XNA

I created a simple Grid-Display system for debugging my games.
Pretty useful when I want to know the position of any object in the game.
It helps a lot in visualization.

Required class members:
public int Width;
public int Height;
public int Rows;
public int Columns;
public Vector3 Position;
List<VertexPositionColor> vertices;
BasicEffect effect;
Game game;

Constructor:
public Grid(Vector3 Position, int Width, int Height, int Rows, int Columns, Game game)

Constructor logic:
this.game = game;
effect = new BasicEffect(game.GraphicsDevice, null);
effect.VertexColorEnabled = true;  
this.Width = Width;
this.Height = Height;
this.Rows = Rows;
this.Columns = Columns;
this.Position = Position;
vertices = new List<VertexPositionColor>();
int xDiff = this.Width / this.Columns;
int zDiff = this.Height / this.Rows;
float xBase = this.Position.X - this.Width/ 2f;
float zBase = this.Position.Z - this.Height / 2f;
float yBase = this.Position.Y;
for (int i = 0; i <= this.Rows;i++)
{
   vertices.Add(new VertexPositionColor(new Vector3(xBase + i * xDiff, yBase, zBase), Color.Green));   vertices.Add(new VertexPositionColor(new Vector3(xBase + i * xDiff, yBase, zBase + this.Height), Color.Green));
}
for (int i = 0; i <= this.Columns;i++)
{
   vertices.Add(new VertexPositionColor(new Vector3(xBase, yBase, zBase + i* zDiff), Color.Green));
   vertices.Add(new VertexPositionColor(new Vector3(xBase + this.Width, yBase, zBase + i * zDiff), Color.Green));
}

The Draw method:
public void Draw()
{
     game.GraphicsDevice.VertexDeclaration = new VertexDeclaration(game.GraphicsDevice, VertexPositionColor.VertexElements);
     effect.Begin();
     foreach (EffectPass pass in effect.CurrentTechnique.Passes)
     {
        pass.Begin();
        effect.View = Camera.View;
        effect.Projection = Camera.Projection; 
        //Draw vertices as Primitive                 
       effect.End();
     }    
     effect.End();
}

To draw the lines:
game.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList,vertices.ToArray(),0,vertices.Count/2);

Logic explained:
Assume that the given position is the center of the Grid.
Grid extends on each side, i.e x and z axis by the amount width/2 and height/2.
The xDiff and xDiff are the distance between each column and row.
Start adding lines for each column and row.
Note the <= operator for the loop construct!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.