How to translate from World to Screen pos?

Despite the different resources and examples, I have not been able to understand how to translate a world pos to a screen pos.

I have a simple scene with a cube placed in [0, 0, 0] and a perspective camera placed in [0, 0, 10], looking towards the cube.

This is how I translate the cube position:

        const cubePos = this.cube.position;
        const screenPos = this.Camera3D.worldToScreen(cubePos);

        console.log("Cube screen position X is " + screenPos.x);

Now, when I place the cube on the left corner of the screen, the X value being logged in 0, which I suppose makes sense because the function uses a bottom-left anchor.

But if I place the cube on the right side of the screen, the value becomes something close to 280. Why 280? I am playing in 1080x1920.

Can someone give me some insight of how this is supposed to work?

Please note that worldToScreen has two params you should input.

The result is the same regarless of what I do:

This:

        const screenPos = this.Camera3D.worldToScreen(cubePos);

This:

        let pos = new Vec3();
        this.Camera3D.worldToScreen(cubePos, pos);

Or even this:

        let pos = new Vec3();
        this.Camera3D.camera.worldToScreen(pos, cubePos);

give the same result.

What I don’t understand is how is the worldToScreen calculated and what is this “280” referring to.

Okay I’ve finally understood. The worldToScreen() function calculates the position according to the ACTUAL window size. I am testing the game in the editor preview. That means that if I zoom in/out the game preview, the calculated screen pos will change as well.

So I have to compensate with a ratio between the visible view size and the screen size:


        let pos = new Vec3();
        this.Camera3D.worldToScreen(new Vec3(cubePos.x, cubePos.y, cubePos.z), pos);


        console.log(pos.x * (view.getVisibleSize().x / screen.windowSize.x)); // This logs a value between 0 and my actual view size, 1080 in my case.

Is this behavior really intended? :slight_smile: