我目前正在开发一款玩家可以破坏地形的游戏。不幸的是,在我的地形纹理上使用 SetData
方法后,我得到了这个异常:
You may not call SetData on a resource while it is actively set on the GraphicsDevice. Unset it from the device before calling SetData.
现在,在有人说还有关于此问题的其他主题之前,我已经查看了所有这些主题。他们都说要确保不要调用Draw()
中的方法,但我只在Update()
中使用它。这是我目前用来破坏地形的代码:
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);
}
}
每当鼠标在地形上单击时,我想将图像中 20 像素半径内的所有像素更改为透明。 GetPositionOfTextureData()
所做的只是返回一个包含像素在纹理数据中的位置的 Vector2
。
我们将不胜感激。
最佳答案
您必须通过调用以下方法解除纹理与 GraphicsDevice 的绑定(bind):
graphicsDevice.Textures[0] = null;
在尝试通过 SetData 写入之前。
关于c# - XNA C# 可破坏地形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772808/