Directx 3D越远的对象覆盖越近的对象

Directx 3D越远的对象覆盖越近的对象,directx,managed-directx,Directx,Managed Directx,我是c#中DirectX的新手,有一个问题让我很困惑,基本上我想在屏幕上渲染两个立方体,一个离摄像机很近,另一个离摄像机很远,我期望的是越近的立方体总是在另一个的前面,但事实上,这取决于渲染顺序,最后一个渲染总是在另一个之前,我试图清除z缓冲区,但这根本不起作用,所以我想知道是否有什么地方我做错了 下面是我的代码片段 private void Form1_Load(object sender, EventArgs e) { PresentParameters presen

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

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

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


但是我不知道原因,也不知道为什么会这样,有人知道吗?

你必须理解透视投影。透视矩阵设置投影,使投影为x'=xstuff/zstuff,y'=ystuff/zstuff。z'=1/z*东西。对于x和y,它通过选择正确的内容将像素坐标映射到-1,1范围。但它也必须对z做同样的事情。通过znear和zfar,你可以告诉它你感兴趣的东西。和你对x和y所做的一样。窗口大小的宽度。但是因为znear=0将导致z'=z/0,所以这将不起作用。你不能有无限的z精度!非常感谢,我现在明白了。
Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 10000.0f);