XNA C#可破坏地形

时间:2012-10-07 21:00:11

标签: c# xna 2d textures terrain

我目前正在制作一款玩家可以破坏地形的游戏。不幸的是,在我的地形纹理上使用SetData方法后,我得到了这个异常:

  

在资源上激活时,您可能无法在资源上调用SetData   GraphicsDevice的。在调用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,其中包含纹理数据中像素的位置。

非常感谢所有帮助。

1 个答案:

答案 0 :(得分:1)

您必须通过调用:

从GraphicsDevice取消绑定纹理
  graphicsDevice.Textures[0] = null;
在尝试通过SetData写入它之前

相关问题