我尝试在 rendertarget2d 中绘制我的 3d 世界。如果我使用默认的渲染目标,世界看起来很完美......但如果我渲染到渲染目标2d,z 缓冲区将不起作用,并且背景中的对象将被绘制在其他人面前。
rendertarget2d 是正确的类吗?我做错了什么?
public class Camera
{
public Matrix View { get; set; }
public Matrix Projection { get; set; }
public RenderTarget2D RenderTarget { get; set; }
public Vector2 Screen { get; set; }
public Effect ZBufferEffect { get; set; }
private GraphicsDevice device;
public void Draw(SpriteBatch spriteBatch, Player player, SpriteFont font)
{
device.SetRenderTarget(RenderTarget);
device.Clear(Color.Black);
device.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
// Draw the scene
View = Matrix.Invert(Object.OBJECTS[0].PosRotSca);
View *= Matrix.CreateTranslation(0, -5, -5);
View *= Matrix.CreateRotationX(MathHelper.ToRadians(20));
foreach(Object obj in Object.OBJECTS)
{
foreach(ModelMesh mesh in Game1.modelArray[obj.Model].Meshes)
{
//foreach (ModelMeshPart part in mesh.MeshParts)
//{
// part.Effect = ZBufferEffect;
// ZBufferEffect.Parameters["World"].SetValue(obj.PosRotSca * mesh.ParentBone.Transform);
// ZBufferEffect.Parameters["View"].SetValue(View);
// ZBufferEffect.Parameters["Projection"].SetValue(Projection);
// ZBufferEffect.Parameters["ModelTexture"].SetValue(Game1.textureArray[obj.Texture]);
// ZBufferEffect.Parameters["invert"].SetValue(false);
//}
foreach (BasicEffect effect in mesh.Effects)
{
effect.Texture = Game1.textureArray[obj.Texture];
effect.TextureEnabled = true;
effect.World = obj.PosRotSca;
effect.View = View;
effect.Projection = Projection;
}
mesh.Draw();
}
}
device.SetRenderTarget(null);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend,
SamplerState.LinearClamp, DepthStencilState.Default,
RasterizerState.CullNone);
spriteBatch.Draw(RenderTarget, new Rectangle(0, 0, device.Viewport.Width, device.Viewport.Height), Color.White);
spriteBatch.End();
}
public Camera(GraphicsDevice device)
{
RenderTarget2D rt = new RenderTarget2D(
device,
device.PresentationParameters.BackBufferWidth,
device.PresentationParameters.BackBufferHeight,
false,
device.PresentationParameters.BackBufferFormat,
DepthFormat.Depth24);
RenderTarget = rt;
this.device = device;
}
}
我可以更改渲染目标中的一些设置吗?还是我必须编写一个 Z 缓冲区着色器?感谢您的帮助!