Phaser.io 3: Get game size in scene

Viewed 16462

It seems to be a simple question, but I just cannot resolve it:

I'm using Phaser.io 3 HTML5 game framework with ES6 classes, and I try to figure out the actual "Game Size" (or canvas / viewport size), so that I can center an object on screen:

class Scene1 extends Phaser.Scene {
    constructor(config) {
        super(config);
    }

    preload() {
        this.load.image('ship', 'assets/spaceship3.png');
    }

    create() {

        let ship = this.add.sprite(160,125, 'ship');
        // Here I need to figure out the screen width / height:
        // ---> How do I achieve that?
        ship.setPosition(width / 2, height / 2);
    }
}

I could not find a way to either read or calculate the actual viewport's / canvas' size. Any hints?

4 Answers

In a scene, in the preload() and create() methods (not in the constructor) you can access the canvas element with this.sys.game.canvas. So to get the canvas size, you can do:

create() {
    let { width, height } = this.sys.game.canvas;
}

For my part I like to add the following code to ease the access to the canvas:

preload() {
    this.canvas = this.sys.game.canvas;
}

You can use the default camera:

ship.setPosition(this.cameras.main.centerX, this.cameras.main.centerY);

From the Phaser 3 API Documentation on Camera:

Cameras, by default, are created the same size as your game, but their position and size can be set to anything.

The following should work:

scene.sys.game.scale.gameSize

I use the following code in my preload to get both the width and height.

    this.gameWidth = this.sys.game.canvas.width
    this.gameHeight = this.sys.game.canvas.height
Related