Wednesday, April 4, 2018

xna - 2D Grid based game - how should I draw grid lines?


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!



Answer



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!


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...