【发布时间】:2012-10-07 21:00:10
【问题描述】:
我目前正在开发一款玩家可以破坏地形的游戏。不幸的是,在我的地形纹理上使用SetData 方法后,我遇到了这个异常:
您不能在资源上主动设置资源时调用 SetData 图形设备。在调用 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,其中包含纹理数据中像素的位置。
所有帮助将不胜感激。
【问题讨论】:
-
而this question 没有帮助?
-
您似乎也没有使用 spriteBatch.begin();和 spriteBatch.end()。这也可能是个问题。
-
没关系,非常感谢!我一直认为纹理是静态的。
标签: c# xna 2d textures terrain