Attach Custom Update Function to Pixi.js Ticker

This article provides a straightforward guide on how to attach a custom update function to the main game loop using the Pixi.js Ticker. You will learn how to access the ticker from your Pixi.js Application, write a compatible update function that utilizes delta time, and register or remove your function to ensure smooth, frame-rate-independent animations.

Understanding the Pixi.js Ticker

In Pixi.js, the Ticker is a helper class that runs a update loop (usually driven by requestAnimationFrame) and calls registered callback functions on every frame. By default, every PixiJS Application instance comes with an internal ticker (app.ticker) that is automatically started.

Step 1: Create Your Custom Update Function

Your custom update function is where you place game logic, such as moving sprites, updating physics, or checking for collisions. Pixi.js automatically passes a ticker object (or a delta time value, depending on the version) to your callback function.

// A simple custom update function
function update(ticker) {
    // Get the delta time to ensure smooth movement across different frame rates
    const delta = ticker.deltaTime;

    // Example: Rotate a sprite
    mySprite.rotation += 0.01 * delta;
}

Step 2: Attach the Function to the Ticker

To add your custom function to the game loop, use the .add() method of the app.ticker instance. This registers the function to be executed once per frame.

import { Application, Sprite } from 'pixi.js';

// Initialize the PixiJS Application
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

// Create a sprite (assuming 'mySprite' is loaded and added to the stage)
const mySprite = Sprite.from('player.png');
app.stage.addChild(mySprite);

// Custom update function
function update(ticker) {
    mySprite.x += 2 * ticker.deltaTime;
}

// Attach the update function to the main game loop
app.ticker.add(update);

Step 3: Controlling the Ticker

You can also pause, resume, or remove your update function dynamically during runtime.

Removing the Update Function

If you need to stop your custom function from running (for example, when pausing the game or switching scenes), use the .remove() method:

// Remove the specific update function from the loop
app.ticker.remove(update);

Pausing the Entire Ticker

To stop the entire update loop completely:

// Stop the ticker
app.ticker.stop();

// Resume the ticker
app.ticker.start();