4
\$\begingroup\$

I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine.

But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d/2d rendering?

Like so:

Example

Thanks!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Which is best? According to what criteria? Speed? Ease of implementation? Idiomaticness? In the case of the latter two, I'd guess to ask the question ("Should I really be switching between sprites and 3d/2d rendering?") is to answer it. \$\endgroup\$
    – Eric
    Oct 2 '12 at 15:35
  • \$\begingroup\$ Right you are. I think the criteria was both performance and ease of implementation, I maybe didn't really word it right, but I came up with a neat fix, below. And you're right in that asking the question answers it really. A good insight! Thanks \$\endgroup\$ Oct 2 '12 at 15:39
  • 1
    \$\begingroup\$ @AdamKDean, i have a nice library just for drawing simple primitives: www.drippingflames.com/xna \$\endgroup\$ Oct 2 '12 at 17:32
  • 1
    \$\begingroup\$ Personally I prefer primitives because, if you add a zoom feature, when you zoom in they will "shrink" in width allowing you to more clearly see the tile boundaries. \$\endgroup\$ Oct 3 '12 at 6:42
8
\$\begingroup\$

Figured out an easy way to do it. Should have been obvious to me to begin with.

First I create a 1px texture:

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

Then I just draw stretched sprites as lines, rather than creating long sprite pngs:

for (float x = -cols; x < cols; x++)
{
    Rectangle rectangle = new Rectangle((int)(centerX + x * gridSize), 0, 1, height);
    spriteBatch.Draw(texture1px, rectangle, Color.Red);
}
for (float y = -rows; y < rows; y++)
{
    Rectangle rectangle = new Rectangle(0, (int)(centerY + y * gridSize), width, 1);
    spriteBatch.Draw(texture1px, rectangle, Color.Red);
}

And I get:

grid

Hope this helps someone, some day!

\$\endgroup\$
2
  • 6
    \$\begingroup\$ +1, Yeah, exactly. Me and a friend wrote a little extension library that helps draw lines and other primitives. \$\endgroup\$ Oct 2 '12 at 15:50
  • \$\begingroup\$ Thanks again for the share @JohnMcDonald, that class will make my life a lot easier. \o \$\endgroup\$ Oct 2 '12 at 16:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .