c# - XNA C# 可破坏地形

标签 c# xna 2d textures terrain

我目前正在开发一款玩家可以破坏地形的游戏。不幸的是,在我的地形纹理上使用 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/

相关文章:

c# - C++ 作为 Windows 游戏编程的第一语言?

java - OpenGL - 矩阵运算

c# - 在 .Net 2.0 中关闭 SerialPort 时出现 ObjectDisposedException

C# - 为什么构造函数不写入初始化值?

c# - Hook 键盘复制输入(c#/xna)

c# - 调整数组大小会调用 GC 吗?

javascript - 烘焙转换为 SVG 路径元素命令

Java 2D 游戏 KeyListener 没有实现它的命运

c# - 如何打开目录以在其上流式传输

c# - 为什么 C++ 和 C# 对 double 类型有不同的最大值的解释?