Search code examples
phaser-framework

Phaser.io 3: Get game size in scene


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?


Solution

  • 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.