I am developing a Monogame project where I have a map class like this:
public class Map{ private RenderTarget2D _target; public const int TILE_SIZE = 128; public static readonly int[,] tiles = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 1, 0, 1, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 1, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 1, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }; Texture2D wall = Globals.Content.Load<Texture2D>("wall"); public Map() { _target = new(Globals.GraphicsDevice, tiles.GetLength(1) * TILE_SIZE, tiles.GetLength(0) * TILE_SIZE); Activate(); DrawMap(); Globals.GraphicsDevice.SetRenderTarget(null); } public void Explosion() { tiles[0,0] = 0; Activate(); DrawMap(); Globals.GraphicsDevice.SetRenderTarget(null); } public void Activate(){ Globals.GraphicsDevice.SetRenderTarget(_target); Globals.GraphicsDevice.Clear(Color.Transparent); } public void DrawMap(){ Globals.SpriteBatch.Begin(); for (int i = 0; i < tiles.GetLength(0); i++) { for (int j = 0; j < tiles.GetLength(1); j++) { if (tiles[i, j] == 1) { var posX = j * TILE_SIZE; var posY = i * TILE_SIZE; Globals.SpriteBatch.Draw(wall, new Vector2(posX, posY), Color.White); } } } Globals.SpriteBatch.End(); } public void Draw() { Globals.SpriteBatch.Draw(_target, Vector2.Zero, Color.White); } public void Update() { }}
The tiles matrix is the layout of the map, lets say there is an explosion at tile[0,0] (Explosion method). How can I redraw the changed map to the screen? Right now it crashes can't figure out why. There is also a GameManager class where i create a map instance and call it's Draw() method but that's it.
I tried playing around with the SpriteBatch.Begin - End, but it doesn't seems to be the problem, The crash happens after calling Activate() method the second time. Maybe there is something I don't understand about RenderTarget2D is the problem here.