Home > Software engineering >  Three.js - get screen position with no camera
Three.js - get screen position with no camera

Time:05-18

I need to calculate screen position outside of Three, with with no camera present.

I know the object position, camera position and camera target

I've seen lots of instructions such as three.js Vector3 to 2D screen coordinate with rotated scene

vector.project(camera);
vector.x = Math.round( (   vector.x   1 ) * w / 2 );
vector.y = Math.round( ( - vector.y   1 ) * h / 2 );

I understand Vector.project camera takes into account the camera settings, FOV etc I'd assume?

Vector3 has projectOnVector(), does this do the same thing as vector3.project(camera) ?

Is there a way to calculate where the object would be on screen without being able to access the camera?

CodePudding user response:

Yes, the Vector3.project takes into account the camera settings...

You need to calculate a projection matrix as you are trying to transform a position from world space to view space. This is a great little animation describing the journey that point will make: https://jsantell.com/model-view-projection/mvp.webm (lifted from this useful page: https://jsantell.com/model-view-projection/).

If you look in the three source code it will show you everything you need to do this. Vector3.project is just applying the two matrices from the camera:

return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );

So how do you get these matrices? The project matrix is generated here.

You can ignore the view, skew and zoom, so you just need near, far, aspect and fov.

updateProjectionMatrix() {

    const near = this.near;
    let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
    let height = 2 * top;
    let width = this.aspect * height;
    let left = - 0.5 * width;

    this.projectionMatrix.makePerspective( left, left   width, top, top - height, near, this.far );
}

If you need makePerspective it is here

The matrixWorldInverse is just that... take your world matrix and inverse it. Three.js does it here.

This gives you your view matrix. So, view matrix multiplied with the projection gives you your screen space position... just like in a shader i.e:

gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0); I'm assuming your point is in world space so you can ignore the model part as this just takes you from model to world.

  • Related