I am currently working on a game in which players can destruct the terrain. Unfortunately, I am getting this exception after using the SetData
method on my terrain texture:
You may not call SetData on a resource while it is actively set on the GraphicsDevice. Unset it from the device before calling SetData.
Now, before anyone says that there are other topics on this problem, I have looked at all of those. They all say to make sure not to call the method within Draw()
, but I only use it in Update()
anyways. Here is the code I am currently using to destruct the terrain:
public class Terrain
{
private Texture2D Image;
public Rectangle Bounds { get; protected set; }
public Terrain(ContentManager Content)
{
Image = Content.Load<Texture2D>("Terrain");
Bounds = new Rectangle(0, 400, Image.Width, Image.Height);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Image, Bounds, Color.White);
}
public void Update()
{
if (Globals.newState.LeftButton == ButtonState.Pressed)
{
Point mousePosition = new Point(Globals.newState.X, Globals.newState.Y);
if(Bounds.Contains(mousePosition))
{
Color[] imageData = new Color[Image.Width * Image.Height];
Image.GetData(imageData);
for (int i = 0; i < imageData.Length; i++)
{
if (Vector2.Distance(new Vector2(mousePosition.X, mousePosition.Y), GetPositionOfTextureData(i, imageData)) < 20)
{
imageData[i] = Color.Transparent;
}
}
Image.SetData(imageData);
}
}
}
private Vector2 GetPositionOfTextureData(int index, Color[] colorData)
{
float x = 0;
float y = 0;
x = index % 800;
y = (index - x) / 800;
return new Vector2(x + Bounds.X, y + Bounds.Y);
}
}
}
Whenever the mouse clicks on the terrain, I want to change all pixels in the image within a 20 pixel radius to become transparent. All GetPositionOfTextureData()
does is return a Vector2
containing the position of a pixel within the texture data.
All help would be greatly appreciated.