0

我是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();
    }
4

1 回答 1

0

好吧,我终于解决了这个问题,通过改变

Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0f, 10000.0f);

Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 10000.0f);

但我不知道原因,为什么会发生,有人知道吗?

于 2015-06-04T05:05:24.457 回答