Project world position to screen coordinate system

I want to project the world position to screen. And i found Vector3.project(camera). But I got Infinity.

var geom = new THREE.SphereGeometry(0.1,30,30);
var mat = new THREE.MeshBasicMaterial({color: 0xffffff});
var mesh = new THREE.Mesh(geom, mat);
mesh.position.set(1,2,0);
scene.add(mesh);

var position = mesh.position.clone();
position.project(camera);
console.log(position)

screen
So how to project world position to screen coordinate system correctly?

You have to call camera.updateMatrixWorld(); before you use Vector3.project().

https://jsfiddle.net/f2Lommf5/5772/

4 Likes

thank you very much.it wworks!:grin:

There is not a lot of documentation on the reason. If could tell briefly why one does need to do that before projecting a Vector please, that’d be helpful. Thanks.

Because Vector3.project() uses camera.matrixWorldInverse which is calculated by calling Camera.updateMatrixWorld().

4 Likes

I should have read the codebase, my bad. Thanks much tho.

related question: how about when you change the viewport as well? cause it doesn’t seem to work as expected if you set the viewport!
here the screenshots:

Of course camera.projectionMatrix is also used, so yes, you have to call camera.updateProjectionMatrix();

Usually this is done in the onWindowResize() event handler in all the examples.

1 Like

Saved my day!

1 Like