How to Dynamically Adjust Animation Frame Rate Based on Distance and Visibility?

I’m currently working on a Babylon.js project involving multiple animated models in a scene. For performance optimization, I’m seeking a method to reduce the animation frequency for models when they are far from the camera and cease the animation of off-screen models entirely.

Previously, I had patched the PlayCanvas engine to support a similar feature using a fixed timestep. Here’s a snippet of what I did:

const animationComp = component.entity.animation;
// --- check if we have requested a fixed timestep for this component
if(animationComp.fixedTimestep > 0.0){
    if(!animationComp.fixedTimer) animationComp.fixedTimer = 0.0;
    animationComp.fixedTimer += dt;
    // --- check if we should be updating it
    if(animationComp.fixedTimer < animationComp.fixedTimestep) continue;
    // --- update animation using the total delta                        
    dt = animationComp.fixedTimer;
    animationComp.fixedTimer = 0.0;

I’m wondering if there’s a way to implement something similar in Babylon.js. Does the API support such functionality, or will I need to find an alternative approach? Any guidance or examples would be incredibly helpful.

Thanks in advance!

Hello and welcome to the Babylon forum!

You can pause an animation when it’s not in the main camera’s frustrum and restart it when it re-enters the frustrum. Here’s an example: Note that the animation may take the target mesh out of the frustrum, so you may need to add an invisible bounding box around the mesh’s animated extents to use for the camera’s frustrum test instead of using the mesh directly.

To animate on a fixed time step you can pause the animation and update its frame manually in the scene’s onAfterRenderObservable when the fixed time step expires. Here’s an example:


Thank you so much for the warm welcome and your detailed answer. It has been very helpful!