我在XNA项目中有一个标准的800x600窗口。我的目标是根据一个矩形数组中的布尔值为每个像素着色。目前我正在使用1x1纹理并绘制数组中的每个精灵。
我非常新于XNA,来自GDI背景,所以我正在做我在GDI中会做的事情,但它不太可扩展。在另一个问题中,有人告诉我要使用Shader,但经过多次研究,我仍然无法找到如何实现这个目标。
我的应用程序循环遍历矩形数组的X和Y坐标,根据每个值进行计算,并重新分配/移动数组。最后,我需要使用新值更新我的"画布"。较小的数组示例如下:
我非常新于XNA,来自GDI背景,所以我正在做我在GDI中会做的事情,但它不太可扩展。在另一个问题中,有人告诉我要使用Shader,但经过多次研究,我仍然无法找到如何实现这个目标。
我的应用程序循环遍历矩形数组的X和Y坐标,根据每个值进行计算,并重新分配/移动数组。最后,我需要使用新值更新我的"画布"。较小的数组示例如下:
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
1,1,1,1,1,1,1
1,1,1,1,1,1,1
如何使用着色器为每个像素上色?
一个非常简化的计算版本如下:
for (int y = _horizon; y >= 0; y--) // _horizon is my ending point
{
for (int x = _width; x >= 0; x--) // _width is obviously my x length.
{
if (grains[x, y] > 0)
{
if (grains[x, y + 1] == 0)
{
grains[x, y + 1] = grains[x, y];
grains[x, y] = 0;
}
}
}
}
每次调用更新方法时,都会进行计算。对于上述循环的示例,更新可能如下所示:
初始:
0,0,0,1,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
1,1,1,0,1,1,1
1,1,1,1,1,1,1
首先:
0,0,0,0,0,0,0
0,0,0,1,0,0,0
0,0,0,0,0,0,0
1,1,1,0,1,1,1
1,1,1,1,1,1,1
第二点:
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,1,0,0,0
1,1,1,0,1,1,1
1,1,1,1,1,1,1
最终结果:
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
1,1,1,1,1,1,1
1,1,1,1,1,1,1
更新:
在应用Render2DTarget代码并放置像素后,我的像素上出现了一个不想要的边框,总是在左边。我如何去掉它?
alt text http://www.refuctored.com/borders.png
alt text http://www.refuctored.com/fallingdirt.png
应用纹理的一些代码如下:
RenderTarget2D target;
Texture2D texture;
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
texture = Content.Load<Texture2D>("grain");
_width = this.Window.ClientBounds.Width - 1;
_height = this.Window.ClientBounds.Height - 1;
target = new RenderTarget2D(this.GraphicsDevice,_width, _height, 1, SurfaceFormat.Color,RenderTargetUsage.PreserveContents);
}
protected override void Draw(GameTime gameTime)
{
this.GraphicsDevice.SetRenderTarget(0, target);
this.GraphicsDevice.SetRenderTarget(0, null);
this.GraphicsDevice.Clear(Color.SkyBlue);
this.spriteBatch.Begin(SpriteBlendMode.None,SpriteSortMode.Deferred,SaveStateMode.None);
SetPixels(texture);
this.spriteBatch.End();
}
private void SetPixels(Texture2D texture)
{
for (int y = _grains.Height -1; y > 0; y--)
{
for (int x = _grains.Width-1; x > 0; x--)
{
if (_grains.GetGrain(x, y) >0)
{
this.spriteBatch.Draw(texture, new Vector2(x,y),null, _grains.GetGrainColor(x, y));
}
}
}
}