Pixi TutorialTutorial

Pixi.js – Creating a game with the PIXI Application Class

In version 4.3.3, Pixi added in a application class. From the documentation – “Convenience class to create a new PIXI application. This class automatically creates the renderer, ticker and root container.”

You can take a look at how we would setup the game previously, however thanks to the application class, this has become far easier. So lets look at an example of how to set one up.


// as per the documentation
// Create the application
const app = new PIXI.Application();
// Add the view to the DOM
document.body.appendChild(app.view);
// ex, add display objects
app.stage.addChild(PIXI.Sprite.fromImage('something.png'));

Lets take a look at how to set this up in Typescript.


export default class Game {
private _app:PIXI.Application;
constructor() {
this._app = new PIXI.Application();
document.body.appendChild(this._app.view);
}
public get stage():PIXI.Container {
return this._app.stage;
}
public get ticker():PIXI.ticker.Ticker {
return this._app.ticker;
}
}

So we just created a quick ‘Game’ class, and made a couple of getters for easier reference. To show you why it’s easier to reference, examine the following.


import Game from './../Game;
// import the game class
export default class SomeView extends PIXI.Container {
// holds a reference to the instantiated game class
private game:Game;
constructor(game:Game) {
// as we're extending a class, we need to call the inherited classes constructor first
super();
// store a reference to the game
this.game = game;
// add this view to the game 
this.game.stage.addChild(this);
// create a new sprite and add a texture to it
let awesomeSprite = new PIXI.Sprite();
awesomeSprite.texture = PIXI.Texture.fromImage('something.png');
// add the sprite to this view (container)
this.addChild(awesomeSprite);
}
}

So above is an example of using views. A view extends a Pixi Container and we just add this view to the stage. We can then add any display object to our view, and it will automatically get added to the game stage. This isn’t specific to the Pixi Application class, just thought I’d throw it on here as a good example of why it’s useful to make getters for your stage.

Tags

Nicholas Mordecai

Just your friendly neighbourhood programmer!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close
Close