【发布时间】:2011-02-14 20:38:40
【问题描述】:
我必须使用 XNA 在 3d 模型上创建 2d 菜单。现在,我已经为 2D 和 3d 模型创建了 spritebatch。但是,正如我注意到的,并在其他地方提到过,由于 z 缓冲区问题,模型没有正确显示。根据教程,我应该在 draw 方法中再次启用 DepthBuffer。但是,不知何故,当我使用:
GraphicsDevice.DepthStencilState.DepthBufferEnable = true;
代码在调试过程中抛出一个错误,说,
无法更改只读的 DepthStencilState。状态对象在第一次绑定到 GraphicsDevice 时变为只读。要更改属性值,请创建一个新的 DepthStencilState 实例。
现在,我也尝试创建 DepthStencilState 的新实例,但是,即使这样似乎也不起作用。我总是得到同样的错误,即使帮助文档建议它的读/写值。
请帮我弄清楚如何正确显示 3D 模型。
这里是绘制代码供参考。
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
Matrix[] transforms = new Matrix[myModel.Bones.Count];
myModel.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in myModel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
//effect.DirectionalLight0.Enabled = true;
//effect.DirectionalLight0.DiffuseColor = Color.AntiqueWhite.ToVector3();
//effect.DirectionalLight0.Direction = new Vector3(0, 0, 0);
effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(myModelRotation) * Matrix.CreateTranslation(myModelPosition);
effect.View = Matrix.CreateLookAt(new Vector3(0, 0, 3000), Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45f),
GraphicsDevice.Viewport.AspectRatio, 1, 5000);
}
mesh.Draw();
}
spriteBatch.Begin();
spriteBatch.Draw(myTexture, new Vector2(0, 0), Color.White);
spriteBatch.End();
DepthStencilState d = new DepthStencilState();
d.DepthBufferEnable = true;
GraphicsDevice.DepthStencilState = d;
base.Draw(gameTime);
}
【问题讨论】: