Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

THREE.js converting from 3D vector to 2D pixel position, interpreting z coordinate

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?

like image 712
Carpetfizz Avatar asked Oct 15 '25 19:10

Carpetfizz


1 Answers

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.

like image 51
WAFFO Avatar answered Oct 18 '25 09:10

WAFFO