gpt4 book ai didi

xna - 通过将 2D Sprite 与 3D 模型混合来解决 Z 缓冲区问题

转载 作者:行者123 更新时间:2023-12-04 02:58:35 24 4
gpt4 key购买 nike

我必须使用 XNA 在 3d 模型上创建一个 2d 菜单。现在,我已经为 2D 和 3D 模型创建了 spritebatch。但是,正如我所注意到的,并在其他地方提到过,由于 z 缓冲区问题,模型无法正确显示。根据教程,我应该在 draw 方法中再次启用 DepthBuffer。但是,不知何故,当我使用:

GraphicsDevice.DepthStencilState.DepthBufferEnable = true;

代码在调试期间抛出错误,说,

Cannot change read-only DepthStencilState. State objects become read-only the first time they are bound to a GraphicsDevice. To change property values, create a new DepthStencilState instance.



现在,我也尝试创建一个 DepthStencilState 的新实例,但是,即使这样似乎也不起作用。我总是遇到同样的错误,即使帮助文档建议它是读/写值。

请帮助我弄清楚如何正确显示 3D 模型。

这是 Draw 代码以供引用。
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);
}

最佳答案

一旦在设备上设置了 DepthStencilState 对象,就无法修改它。您应该为要使用的每个唯一深度/模板设置创建一个 DepthStencilState 对象。最理想的是,这些状态只应在您的程序中创建一次,然后在需要时设置到设备上。

如需更多信息,请参阅 State Objects in XNA Game Studio 4.0通过肖恩哈格里夫斯。

其他详细信息:

您将 DepthBufferEnable 设置为 true 但也未将 DepthBufferWriteEnable 设置为 true。与其尝试单独设置这些属性,不如使用框架提供的预构建 DepthStencilState 对象。在渲染模型之前,将 GraphicsDevice.DepthStencilState 设置为 DepthStencilState.Default。这会将 DepthBufferEnable 和 DepthBufferWriteEnable 属性设置为 true。

您还需要将设备上的 BlendState 设置为 BlendState.Opaque。

您需要在绘制模型之前设置这些渲染状态,因为 SpriteBatch.Begin() 会自动将渲染状态更改为 DepthStencilState.None 和 BlendState.AlphaBlend(参见 MSDN Documentation for SpriteBatch.Begin)。

关于xna - 通过将 2D Sprite 与 3D 模型混合来解决 Z 缓冲区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4996988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com