我正在试图弄清楚XNA中的3D渲染是如何工作的,它似乎与DirectX非常相似,这使得它非常直接。
但是我有一种行为,我在用精灵批量绘图时没想到这种行为。
当我只绘制一个三维立方体,没有任何精灵时,我得到了这个结果:http://i.stack.imgur.com/DQAHg.png
但是当我试图以下面的方式在2D精灵(从SpriteBatch中绘制)上绘制它时:
SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
base.Draw(gameTime);
SpriteBatch.End();
shape.Draw(gameTime);
这是我得到的结果:http://imgur.com/7QZlj
这显然是错误的。我的第一个想法是使用正交投影渲染(出于某种原因),但我不确定。
这是我用来绘制立方体的代码,它几乎是来自XNA原语样本的1:1(我还没有开始为游戏开发一个合适的3D框架)所以它可能会很混乱
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
// Create camera matrices, making the object spin.
float time = (float)gameTime.TotalGameTime.TotalSeconds;
Vector3 cameraPosition = new Vector3(0, 0, 2.5f);
float aspect = GraphicsDevice.Viewport.AspectRatio;
float yaw = 3.05f;
float pitch = 5.34f;
float roll = 8.396f;
Matrix world = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll);
Matrix view = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(1, aspect, 1, 10);
// currentPrimitive.Draw(world, view, projection, Color.Red);
// Reset the fill mode renderstate.
GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
Color color = Color.Red;
// Set BasicEffect parameters.
basicEffect.World = world;
basicEffect.View = view;
basicEffect.Projection = projection;
basicEffect.DiffuseColor = color.ToVector3();
basicEffect.Alpha = 1.0f;// color.A / 255.0f;
GraphicsDevice device = basicEffect.GraphicsDevice;
device.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
GraphicsDevice graphicsDevice = basicEffect.GraphicsDevice;
// Set our vertex declaration, vertex buffer, and index buffer.
graphicsDevice.SetVertexBuffer(vertexBuffer);
graphicsDevice.Indices = indexBuffer;
foreach (EffectPass effectPass in basicEffect.CurrentTechnique.Passes)
{
effectPass.Apply();
int primitiveCount = indices.Count / 3;
graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
vertices.Count, 0, primitiveCount);
}
我还应该澄清一下,这不是spritebatch.begin / spritebatch.end的结果,如果我只是开始/结束并且不绘制任何东西,最终结果很好但是如果我绘制一个字体或精灵就会中断立方体。
有人有什么想法吗?
答案 0 :(得分:1)
我建议您在进行GraphicsDevice
方法调用后检查SpriteBatch.End()
设置。当您使用SpriteBatch
时,它会改变GraphicsDevice
中的某些渲染状态。可能值得在GraphicsDevice
之前存储SpriteBatch.Begin()
的值,然后在SpriteBatch.End()
方法调用之后重置它们。