Page 1 of 1

Question about nearZ, farZ, and camera position relationship in perspective projection

Posted: October 27th, 2021, 3:40 pm
by WilsonHuang
I have 600x600 plane square. My goal is render it on screen in 1:1 ratio.
Here is my perspective projection and camera code

Code: Select all

//Perspective
gfx.SetProjection(DirectX::XMMatrixPerspectiveLH(1.0f, 1.0f / Graphics::AspectRatio, 1.0f, 1000.0f));

//camera
//every parameter is 0.0f except range
const auto position = 
        DX::XMVector3Transform(
        DX::XMVectorSet(0.0f, 0.0f, -range, 0.0f),
        DX::XMMatrixRotationRollPitchYaw(aroundX, -aroundY, 0.0f));

    return
        DX::XMMatrixLookAtLH(position, DX::XMVectorZero(),
            DX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)) *
        DX::XMMatrixRotationRollPitchYaw(pitch, -yaw, roll);
When I set nearZ = 1.0f, the camera position.z (range) need to set 800.0f (ScreenWidth) to fill the height (see nearZ_1.png)
However, when I set nearZ = 0.5f, the range need to set 400.0f (half of ScreenWidth) to fill the height. (see nearZ_05.png)
Why? I can't figure out the relationship between nearZ and the screen width
Also the square disappears when I set range = 1000.0f. Why? 1000.0f is not greater than the farZ.

Re: Question about nearZ, farZ, and camera position relationship in perspective projection

Posted: October 30th, 2021, 10:49 pm
by albinopapa
Just a guess here, but I'll try my best.

When you create a projection matrix, it defines the entire area the camera can see. Setting the near Z to 1.f would/should be where the "screen" is. By lowering the near Z, you move the near clip plane or closest viewable plane closer to the camera and increasing the range from nearZ to farZ.

As an experiment, you could create a slider that changes the nearZ and farZ values by 0.01f per step.