Search code examples
javamath3d2dprojection

Project 3D point to 2D screen coordinates


I'm trying to project a point from 3D world space to 2D screen coordinates. I have almost everything worked out but I'm having a hard time actually projecting the point.

The setup is as follows:

Pitch = 90 (all the way up, looking down)

Yaw = 0 (facing north)

Roll = 0 (as normal)

I currently am casting a ray from the camera position through the center of the viewport all the way to the end of the frustum, when debugging the ray the values are 0, -1, 0 which means it's facing down so this seems to be correct. Now what I'm trying to achieve is to project the fixed camera point (point on the middle of the ray) from 3D to 2D.

When rotating the camera the projected point should be at the center of the viewport, which it isn't unfortunately.

The current output:

Viewport 800 x 600

projectTo2D: vector: Vector4f: 0.0 0.0 500.0 1.0
World matrix:
1.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0

View matrix:
0.99999994 0.0 0.0 0.0
0.0 -4.371139E-8 -1.0 2.1855694E-5
0.0 1.0 -4.371139E-8 -500.0
0.0 0.0 0.0 1.0

Projection matrix:
-0.75 0.0 0.0 0.0
0.0 1.0 0.0 0.0
0.0 0.0 1.0000999 -0.10000999
0.0 0.0 1.0 0.0

Projection world view:
-0.74999994 0.0 0.0 0.0
0.0 -4.371139E-8 -1.0 2.1855694E-5
0.0 1.0000999 -4.3715755E-8 -500.14996
0.0 1.0 -4.371139E-8 -500.0

HDC: Vector4f: 0.0 -499.99997 -500.15 -500.00003
NDC: Vector4f: -0.0 0.9999999 1.0002999 1.0
Viewport coordinates: 400.0, 599.99994

Solution

  • Firstly, you are projecting a plain 3d vector. Doing so, you ignore the translation and perspective parts of the matrix. Use a 4d vector with 1 as the w-component.

    Secondly, you are missing the w-clip:

    transform(matrix, vector);
    
    vector.x /= vector.w;
    vector.y /= vector.w;
    vector.z /= vector.w;
    vector.w /= vector.w;