3D coordinate -> 2D screen coordinate NaN error when using Vector3.Project

Hello everyone :wave:

My goal is to convert a mesh’s 3D position (BABYLON.Vector3) into a 2D screen coordinate. Based on my research, the method BABYLON.Vector3.Project is the correct tool to use here.

I am currently able to call BABYLON.Vector3.Project, however, the BABYLON.Vector3 that is returned is always NaN. Any suggestions for how to get a valid value?

Here is my BabylonJS playground example: https://playground.babylonjs.com/#R1F8YU#168

I have seen other examples where BABYLON.Vector3.Project is called inside of scene.onBeforeRenderObservable. However, I am creating a helper function and I would not like to do that.

Please note that the solution shared in another similar thread has the same NaN issue.

After further investigation, I have to come to understand that the NaN error is related to the scene not being ready + observable. At the time of my Vector3.Project call.

The following code showcases a solution:

scene.onReadyObservable.addOnce(() => {
    alert('hi');
    var pos = BABYLON.Vector3.Project(
        //sphere.position, //vector to project
        new BABYLON.Vector3(105.50575334130954, 4.0479745205306, 37.04033141497548),
        BABYLON.Matrix.Identity(), //world matrix
        scene.getTransformMatrix(), //transform matrix
        new BABYLON.Viewport(0,0,canvas.width,canvas.height)
    );
    console.log(pos)
    console.log(pos._isDirty);
    console.log(pos.x);
})

Here is a more robust BabylonJS playground demo: https://playground.babylonjs.com/#R1F8YU#172

4 Likes

You can also use scene.updateTransformMatrix :smiley: Vector3 Explanatory PG | Babylon.js Playground (babylonjs.com)

1 Like