How to re-order zIndex of GUI elements depending on camera distance to meshes


My question is exactly the same as: Set gui Rect renderOrder in Different perspectives , @Deltakosh said on this topic: “register to scene.registerBeforeRender and make sure to set zIndex on your controls based on mesh distance to camera”

Could someone help me sort out a solution ? I’ve put together a simple playground of this problem:

I’d like to see the correct sphere label when rotating the camera.


First check the visibility for a mesh in the camera view. Written by @Pryme8.

var sphere = BABYLON.Mesh.CreateSphere(“sphere1”, 16, 2, scene);
var projectionMatrix = scene.activeCamera.getProjectionMatrix();
var frustumPlanes = BABYLON.Frustum.GetPlanes(projectionMatrix);

Then you can measure the distance to a mesh and use this value. Written by @Dad72.

var dist = camera.position.subtract(mesh.position);


1 Like

Great, thanks for the pointers, will try this tomorrow and post a working playground afterwise :wink:

:tada: , this playground does what I was looking for: , hopefully this will help someone with the same problem in the future.

Note that I need to re-link the mesh to the GUI item after updating zIndex.

Many thanks for the pointers @Galen

1 Like