The Frame Loop

When 3D experiences run in an end user’s browser, the 3D engine will draw, or ‘render’, the 3D scene up to 60 times every second. This is known as the Frame Loop. You may wish to run a script before each render frame, perhaps to implement a custom animation, or to perform a node transformation.

Preparing the Frame Loop

To target the frame loop in a custom behavior, component, or context, you should first make sure to import the useOnBeforeRender function at the top of your custom script as so:

import { useOnBeforeRender } from "@zcomponent/core"

You can then register a handler to the event returned by the useOnBeforeRender(contextManager) function.

The rest of this article provides examples of using this function in custom Behaviors and Components.

Frame Loop in a Behavior

// Imports...
import {useOnBeforeRender } from "@zcomponent/core";

// ...other behavior set up...

/*
 * @zbehavior
 * @zicon favorite
 */
export class MyBehavior extends Behavior<Box> {
    protected zcomponent = this.getZComponentInstance(Scene);
    constructor(contextManager: ContextManager, instance: Box, protected constructorProps: ConstructionProps) {
        super(contextManager, instance);

        // You may use the useOnBeforeRender(contextManager) function
        // only if you have imported it as above
        this.register(useOnBeforeRender(contextManager), dt => {
                // This code is run every render frame
                // dt is the number of milliseconds since the last frame
        });
    }
}

Frame Loop in a Component

// Imports...
import {useOnBeforeRender } from "@zcomponent/core";

// ...other component set up...

/**
 * @zcomponent
 * @zicon favorite
 */
export class CustomThreeJSComponent extends Group {

    constructor(contextManager: ContextManager, constructorProps: ConstructorProps) {
        super(contextManager, constructorProps);

        // ...

        this.register(useOnBeforeRender(contextManager), dt => {
                // This code is run every render frame
                // dt is the number of milliseconds since the last frame
        });
    }
    // ...
}
zapcode branded_zapcode i