我是c#中DirectX的新手,有一个问题让我很困惑,基本上我想在屏幕上渲染两个立方体,一个离相机近,一个离相机远,这是我的预期是较近的总是在较远的前面,但实际上,它取决于渲染顺序,最后渲染的总是在另一个前面,我试图清除 z 缓冲区,但这不起作用全部,所以我想知道我做错了什么?
这是我的代码片段
private void Form1_Load(object sender, EventArgs e)
{
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
presentParams.EnableAutoDepthStencil = true;
presentParams.AutoDepthStencilFormat = DepthFormat.D16;
device = new Device(0, DeviceType.Hardware, this, CreateFlags.MixedVertexProcessing, presentParams);
device.VertexFormat = CustomVertex.PositionColored.Format;
device.RenderState.CullMode = Cull.CounterClockwise;
device.RenderState.Lighting = false;
Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0f, 10000.0f);
device.Transform.Projection = projection;
}
protected override void OnPaint(PaintEventArgs e)
{
Cube a = new Cube(new Vector3(0, 0, 0), 5);
Cube b = new Cube(new Vector3(0, 0, 15), 5);
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkGray, 1, 0);
device.BeginScene();
Matrix viewMatrix = Matrix.LookAtLH(cameraPosition, targetPosition, up);
device.Transform.View = viewMatrix;
device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, 8, 12, a.IndexData, false, a.GetVertices());
device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, 8, 12, b.IndexData, false, b.GetVertices());
device.EndScene();
device.Present();
}