Phaser.js Cheatsheet

Basics

Create a Game


const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    backgroundColor: '#ff0000', // default background color of the game
    scene: [
        /* ... your scenes here ... */
    ],
    /* ... other configuration options ... */
};

const game = new Phaser.Game(config);
                    

Result

Phaser.js game window

Scenes

Create a scene


class MyScene extends Phaser.Scene {
    constructor() {
        super({ key: 'MyScene' });
    }

    preload() { /* ... preload assets ... */ }
    init() { /* ... initialize scene ... */ }
    create() { /* ... create game objects ... */ }
    update() { /* ... update game state ... */ }
}

/* ... Add it in your game configuration ... */
const config = {
    scene: [MyScene],
    /* ... other configuration options ... */
};
                    

Result

Phaser.js game window

Moving between scenes


/* ... Define as many scenes you want ... */
class Scene1 extends Phaser.Scene {
    constructor() {
        super({ key: 'Scene1' });
    }
}

class Scene2 extends Phaser.Scene {
    constructor() {
        super({ key: 'Scene2' });
    }
}

/* ... Add them in your game configuration ... */
const config = {
    scene: [Scene1, Scene2],
    /* ... other configuration options ... */
};

/* ... Move between scenes ... */
this.scene.start('Scene2'); // "Scene2" is the key of the scene
                    

Result

Phaser.js game window

Sprites

Add a Sprite


/* ... in your scene ... */
preload() {
    this.load.image('logo', 'assets/logo.png');
}

create() {
    this.add.sprite(400, 300, 'logo');
}
                    

Result

Phaser.js game window

Sprite position / rotation / scaling


/* ... in your scene ... */
create() {
    this.logo = this.add.sprite(400, 300, 'logo').setOrigin(0.5);
}

update(time, delta) {
    /* ... rotate the sprite around the center ... */
    this.logo.setRotation(this.logo.rotation + delta / 100);
    this.logo.setPosition(
    	400 + 100 * Math.cos(time / 100),
      300
    );
    this.logo.setScale(1 + Math.sin(time / 100) * 0.3);
}
                    

Result

Phaser.js game window

Text

Write text


/* ... in your scene ... */
create() {
    this.add.text(400, 300, 'Hello, Phaser!', {
        fontSize: '32px',
        color: '#000000',
        fontFamily: 'Arial',
    });
}
                    

Result

Phaser.js game window

Input

Handle Mouse click with events


/* ... in your scene ... */
create() {
    this.input.on('pointerdown', (pointer) => {
        console.log('Clicked at: ', pointer.x, pointer.y);
    });
}
                    

Result

Phaser.js game window

Mouse click on Phaser objects


/* ... in your scene ... */
create() {
  this.logo = this.add.sprite(400, 300, 'logo').setInteractive();
  this.logo.on('pointerdown', () => {
      console.log('Clicked on the logo');
  });
}
                    

Result

Phaser.js game window

Handle Keyboard input


/* ... in your scene ... */
create() {
    this.spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);

    /* ... as event ... */
    this.spaceKey.on('down', () => {
        console.log('Space key pressed');
    });
}

/* ... or as poll ... */
update() {
    if (this.spaceKey.isDown) {
        console.log('Space key pressed');
    }
}
                    

Result

Phaser.js game window

Keyboard cursors


create() {
  this.cursors = this.input.keyboard.createCursorKeys();
}

update() {
  if (this.cursors.up.isDown) { /* ... */ }
  if (this.cursors.down.isDown) { /* ... */ }
  if (this.cursors.left.isDown) { /* ... */ }
  if (this.cursors.right.isDown) { /* ... */ }
}
                  

Result

Phaser.js game window

Physics

Arcade Physics


const config = {
  ...
  physics: { default: 'arcade' },
};

this.player = this.physics.add.sprite(400, 300, 'player');

/* ... */
this.player.body.setVelocityX(100);
this.player.body.setBounce(1, 1);
                  

Result

Phaser.js game window

Add physics to existing sprite


this.player = this.add.sprite(400, 300, 'player');
this.physics.add.existing(this.player);
/* ... now you can access to body ... */
this.player.body.setGravity(0, 100);
                

Result

Phaser.js game window

Collision Detection


this.player = this.physics.add.sprite(400, 300, 'player');
this.ground = this.physics.add.staticImage(400, 568, 'ground');
this.platform.setImmovable(true);
this.platform.body.allowGravity = false;

this.physics.add.collider(this.player, this.ground, () => {
  console.log('Player hit the ground!');
});
                  

Result

Phaser.js game window

Audio

Play background music


/* ... in your scene ... */
preload() {
    this.load.audio('bgMusic', ['assets/bg-music.mp3', 'assets/bg-music.ogg']);
}

create() {
    this.bgMusic = this.sound.add('bgMusic', { loop: true }).play();
}
                    

Result

Phaser.js game window

Play SFX


/* ... in your scene ... */
preload() {
    this.load.audio('bark', ['assets/bark.mp3']);
}

create() {
    this.barkSFX = this.sound.add('bark');
}

/* ... play it ... */
this.barkSFX.play();
                    

Result

Phaser.js game window

Animation

Basic Tween


const image = this.add.image(100, 100, 'logo');
const tween = this.tweens.add({
    targets: image,
    duration: 3000,
    /* Any property you want to animate */
    x: 500,
});
                  

Result

Phaser.js game window

Advanced Tweening


const image = this.add.image(100, 100, 'logo');
const tween = this.tweens.add({
  targets: image,
  duration: 1000,
  ease: Phaser.Math.Easing.Quadratic.In,
  y: 550,
  yoyo: true,
  repeat: -1
});
                

Result

Phaser.js game window

Frame by Frame


/* Configure an animation with key 'some_animation' */
this.anims.create({
    key: 'some_animation',
    frames: [
        { key: 'frame1' },
        { key: 'frame2' },
        { key: 'frame3' }
    ],
    frameRate: 8,
    repeat: -1
});

/* Create a sprite and run it */
this.add.sprite(100, 100, 'frame1').play('some_animation');
                

Result

Phaser.js game window

Composition

Container nesting


create() {
    this.logo = this.add.container(400, 300, [
        this.add.image(0, 0, 'logo'),
        this.add.text(0, 40, 'Hello, Phaser!').setOrigin(0.5)
    ]);
}

update(time, delta) {
    /* ... rotation, scaling and position are applied to all elements ... */
    this.logo.setRotation(this.logo.rotation + delta / 100);
}
                    

Result

Phaser.js game window

Group of items as classes


class MyComplexObject extends Phaser.GameObjects.Container {
    constructor(scene) {
        super(scene);
        this.addMultiple([
            scene.add.image(0, 0, 'logo'),
            scene.add.text(0, 200, 'Hello, Phaser!')
        ]);
        scene.add.existing(this); // add the container to the scene
    }
}

/* ... in your scene ... */
create() {
    this.baseLogo = new MyComplexObject(this);
    this.baseLogo.setPosition(400, 300);

    this.anotherLogo = new MyComplexObject(this);
    this.anotherLogo.setPosition(200, 200);
}
                    

Result

Phaser.js game window

Camera

Main Camera follow sprite


/* inside a scene */
this.player = this.add.sprite(0, 0, 'player');
/* Set an area where the camera can pan */
this.cameras.main.setBounds(0, 0, 1920 * 2, 1080 * 2);
/* Set the area of the world */
this.physics.world.setBounds(0, 0, 1920 * 2, 1080 * 2);
this.cameras.main.startFollow(this.player);
                  

Result

Phaser.js game window

Multiple cameras


/* inside a scene */
this.cameras.add(0, 0, 400, 300);
                  

Result

Phaser.js game window

Events

Built-in events handling


this.events.once('prerender', () => { console.log('triggers before the first screen update') })
this.events.on('resume', () => { console.log('triggers when the game exits from pause') })
this.events.off('resume') // remove the event
                

Result

Phaser.js game window

Emit custom events


/* ... scene events ... */
this.events.on('playerDied', () => {});
/* ... somewhere else ... */
this.events.emit('playerDied');

/* ... or game object events ... */
this.player = this.add.sprite(400, 300, 'player');
this.player.on('dead', () => {});
/* ... somewhere else ... */
this.events.emit('dead');
                

Result

Phaser.js game window

Custom event emitters


const emitter = new Phaser.Events.EventEmitter();
emitter.on('customEvent', () => {});
emitter.emit('customEvent');
                

Result

Phaser.js game window