C# MonoGame:模具缓冲区不工作
我正在尝试将阴影添加到基于单游戏的2D游戏中。起初,我只是将半透明的黑色纹理渲染到帧上,但它们有时会重叠,看起来很糟糕: 我尝试先将所有阴影渲染到模具缓冲区,然后使用单个半透明纹理使用模具缓冲区一次绘制所有阴影。但是,它没有按预期工作: 这两个问题是:C# MonoGame:模具缓冲区不工作,c#,windows-phone-8,xna,monogame,C#,Windows Phone 8,Xna,Monogame,我正在尝试将阴影添加到基于单游戏的2D游戏中。起初,我只是将半透明的黑色纹理渲染到帧上,但它们有时会重叠,看起来很糟糕: 我尝试先将所有阴影渲染到模具缓冲区,然后使用单个半透明纹理使用模具缓冲区一次绘制所有阴影。但是,它没有按预期工作: 这两个问题是: 阴影被渲染到场景中 模具缓冲区似乎不受影响:半透明的黑色纹理覆盖整个屏幕 以下是初始化代码: StencilCreator = new DepthStencilState { StencilEnable = true, S
- 阴影被渲染到场景中
- 模具缓冲区似乎不受影响:半透明的黑色纹理覆盖整个屏幕
StencilCreator = new DepthStencilState
{
StencilEnable = true,
StencilFunction = CompareFunction.Always,
StencilPass = StencilOperation.Replace,
ReferenceStencil = 1
};
StencilRenderer = new DepthStencilState
{
StencilEnable = true,
StencilFunction = CompareFunction.Equal,
ReferenceStencil = 1,
StencilPass = StencilOperation.Keep
};
var projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
var halfPixel = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
AlphaEffect = new AlphaTestEffect(GraphicsDevice)
{
DiffuseColor = Color.White.ToVector3(),
AlphaFunction = CompareFunction.Greater,
ReferenceAlpha = 0,
World = Matrix.Identity,
View = Matrix.Identity,
Projection = halfPixel * projection
};
MaskingTexture = new Texture2D(GameEngine.GraphicsDevice, 1, 1);
MaskingTexture.SetData(new[] { new Color(0f, 0f, 0f, 0.3f) });
ShadowTexture = ResourceCache.Get<Texture2D>("Skins/Common/wall-shadow");
可能是什么问题?同样的代码在我的XNA项目中运行良好。我通过使用
RenderTarget2D
而不是模具缓冲区来解决这个问题。将实心黑色阴影绘制到RT2D,然后使用半透明颜色将RT2D本身绘制到场景中,这样做的技巧更简单,实现起来也更简单
// create stencil
GraphicsDevice.Clear(ClearOptions.Stencil, Color.Black, 0f, 0);
var batch = new SpriteBatch(GraphicsDevice);
batch.Begin(SpriteSortMode.Immediate, null, null, StencilCreator, null, AlphaEffect);
foreach (Vector2 loc in ShadowLocations)
{
newBatch.Draw(
ShadowTexture,
loc,
null,
Color.White,
0f,
Vector2.Zero,
2f,
SpriteEffects.None,
0f
);
}
batch.End();
// render shadow texture through stencil
batch.Begin(SpriteSortMode.Immediate, null, null, StencilRenderer, null);
batch.Draw(MaskingTexture, GraphicsDevice.Viewport.Bounds, Color.White);
batch.End();