3

I referenced this SO post which explains how to convert a point in 3D space to an actual pixel position on the display. This is the function, copied for convenience.

function toScreenPosition(obj, camera)
{
    var vector = new THREE.Vector3();

    var widthHalf = 0.5*renderer.context.canvas.width;
    var heightHalf = 0.5*renderer.context.canvas.height;

    obj.updateMatrixWorld();
    vector.setFromMatrixPosition(obj.matrixWorld);
    vector.project(camera);

    vector.x = ( vector.x * widthHalf ) + widthHalf;
    vector.y = - ( vector.y * heightHalf ) + heightHalf;

    return { 
        x: vector.x,
        y: vector.y
    };

};

I noticed that vector.z isn't actually 0 after it's been projected using vector.project(camera). For my particular setup, vector.z is ~0.8 (not that it means much for a general question).

So, how should I interpret vector.z? What does it actually represent?

Carpetfizz
  • 8,707
  • 22
  • 85
  • 146

1 Answers1

2

vector.z represents the depth of the point from the screen. Regarding a pixel, or position on the screen, the depth doesn't matter as it doesn't affect the x or y position on the screen. So that component of the vector is not part of the solution, and thus ignored.

As to why it isn't 0, that's because projection multiplies the vertices with the camera matrix. Assuming the camera is positioned to view everything you need, and not pointed somewhere else, the projection function is putting distance (ie depth) between you and the scene.

WAFFO
  • 60
  • 9
  • Thanks, do you mind explaining the last paragraph more? My camera is at z=1 relative to the world (so I can see my object) but everything else is unchanged. What exactly is the distance between “you and the scene”? Especially if it’s in units of pixels – Carpetfizz Jan 09 '19 at 05:48
  • 1
    Shouldn't really think of it in units of pixels, because it would have to be converted like `x` and `y` were, and since monitors don't have depth, it would be a useless representation. Scene was used broadly. So specifically in this function, `vector.z` would be the "distance" between the `camera` and `obj` in the WebGL clip space. For more specifics of the math, I found a cool page that explains the WebGL clip space and projections here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_model_view_projection – WAFFO Jan 09 '19 at 06:32