Displaying rectangles in game window with XNA

blerh picture blerh · May 8, 2010 · Viewed 11.8k times · Source

I want to divide my game grid into an array of rectangles. Each rectangle is 40x40 and there are 14 rectangles in every column, with a total of 25 columns. This covers a game area of 560x1000.

This is the code I have set up to make the first column of rectangles on the game grid:

Rectangle[] gameTiles = new Rectangle[15];

for (int i = 0; i <= 15; i++)
{
    gameTiles[i] = new Rectangle(0, i * 40, 40, 40);
}

I'm pretty sure this works, but of course I cannot confirm it because rectangles do not render on the screen for me to physically see them. What I would like to do for debugging purposes is to render a border, or fill the rectangle with color so I can see it on the game itself, just to make sure this works.

Is there a way to make this happen? Or any relatively simple way I can just make sure that this works?

Thank you very much.

Answer

Callum Rogers picture Callum Rogers · May 9, 2010

First, make a 1x1 pixel texture of white for the rectangle:

var t = new Texture2D(GraphicsDevice, 1, 1);
t.SetData(new[] { Color.White });

Now, you need to render the rectangle - assume the Rectangle is called rectangle. For a rendering a filled block, it is very simple - make sure to set the tint Color to be the colour you want. Just use this code:

spriteBatch.Draw(t, rectangle, Color.Black);

For a border, is it more complex. You have to draw the 4 lines that make up the outline (the rectangle here is r):

int bw = 2; // Border width

spriteBatch.Draw(t, new Rectangle(r.Left, r.Top, bw, r.Height), Color.Black); // Left
spriteBatch.Draw(t, new Rectangle(r.Right, r.Top, bw, r.Height), Color.Black); // Right
spriteBatch.Draw(t, new Rectangle(r.Left, r.Top, r.Width , bw), Color.Black); // Top
spriteBatch.Draw(t, new Rectangle(r.Left, r.Bottom, r.Width, bw), Color.Black); // Bottom

Hope it helps!