Pixi.js – Using the Ticker Class

 

Pixi Ticker

In the previous tutorial we looked at how to create a new PIXI renderer and the request animation frame function. Now, we’re going to improve our update function and use a PIXI Ticker.

The Pixi Ticker class is very helpful. It keeps a track of delta time, which is the time since the last frame and since the game began. Why is this important? Well, if you have very heavy code, there is a chance that your game will make a new RAF request BEFORE the update logic as completed. This is bad, and we want to avoid this at all costs!

So how do we create a new Pixi Ticker? Easily!

Lets add a new private object called Ticker above the constructor and create is in the constructor.


export default class Core {

    private _renderer:PIXI.CanvasRenderer|PIXI.WebGLRenderer;
    private _world:PIXI.Container;
    private _ticker:PIXI.ticker.Ticker;
    
    constructor() {
        this._renderer = PIXI.autoDetectRenderer(400, 400);
        this._world = new PIXI.Container();
        document.body.appendChild(this._renderer.view);
        
        // create the ticker
        this._ticker = PIXI.ticker.shared;
        this._ticker.autoStart = true;
    }

    ...
}

So now you can see that we have created a new ticker and set the autoStart property to true. This just means that as soon as it can, it will start ticking at 60fps.

Auto Start

Now all we need to do, is listen for a tick and add our update function to be called on every tick. The Ticker also takes care of making a RAF request for us.


constructor() {
        ...
        this._ticker.autoStart = true;
        this._ticker.add(this.update, this);
    }

    update() {
        this._renderer.render(this._world);
    }

And that’s it for creating a Pixi Ticker. In the next tutorial, we’ll look at creating a sprite and adding it to our world.

Core Class

As usual, for those copy – paste people, here’s the complete class =)


export default class main {

    private _renderer:PIXI.CanvasRenderer|PIXI.WebGLRenderer;
    private _world:PIXI.Container;
    private _ticker:PIXI.ticker.Ticker;
    
    constructor() {
        this._renderer = PIXI.autoDetectRenderer(400, 400);
        this._world = new PIXI.Container();
        document.body.appendChild(this._renderer.view);
        
        // create the ticker
        this._ticker = PIXI.ticker.shared;
        this._ticker.autoStart = true;
        this._ticker.add(this.update, this);
    }

    update() {
        this._renderer.render(this._world);
    }
}

let game = new Main();