I’m building a 2d top down game with a 1600x1600 map that is built from 32x32 tiles. I start out by constructing the background map RenderTarget2d that gets converted to a Texture2d, set it to a background map object that has a viewport and other handles. It works fine when I have the whole process in the Game1.cs class. Like so:
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
backgroundMap = new RenderTarget2D(GraphicsDevice, 1600, 1600, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents);
Texture2D tile = Content.Load<Texture2D>("blue_32x32.png"); //32x32 tile.
spriteBatch.Begin();
graphics.GraphicsDevice.SetRenderTarget(backgroundMap);
for (int x = 0; x <= 50; x++)
{
for (int y = 0; y <= 50; y++)
{
spriteBatch.Draw(tile, new Vector2(x * 32, y * 32), Color.White); //Draw the tiles into map background.
}
}
spriteBatch.End();
graphics.GraphicsDevice.SetRenderTarget(null);
Texture2D bkgMap = (Texture2D)backgroundMap;
bkg = new BackgroundMap(bkgMap, new Vector2(700, 700), 1f);
}
I want to move this into its own class because the map generator is going to be a procedural system that will grow quite massive. So the above functionality would boil down
MapGenerator mg = new MapGenerator();
Texture2D bkgMap = (Texture2D)mg.GenerateMapTexture( graphics, GraphicsDevice);
But I’m running into trouble getting it to work the way I want to. If I try and move it into another class, one of two things happens.
Either Content.Load fails to run stating “No Graphics Device Service.”
Or I load the texture for the tile in the game class and pass in the graphics device, but if I do that I get a blank white texture back.
What am I doing wrong here? This is the class:
class MapGenerator : Game
{
public Texture2D GenerateMapTexture(GraphicsDeviceManager gdm, GraphicsDevice gd)
{
SpriteBatch batch = new SpriteBatch(gd);
RenderTarget2D map = new RenderTarget2D(gd, 1600, 1600, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents);
Texture2D tile = Content.Load<Texture2D>("blue_32x32.png");//Breaks here saying "No Graphics Device Service"
gdm.GraphicsDevice.SetRenderTarget(map);
batch.Begin();
for (int x = 0; x <= 50; x++)
{
for (int y = 0; y <= 50; y++)
{
batch.Draw(tile, new Vector2(x * 32, y * 32), Color.White);
}
}
batch.End();
batch.Dispose();
gdm.GraphicsDevice.SetRenderTarget(null);
return map;
}
}
Thank you.