Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
Alex Schenkel Avatar asked Sep 02 '18 17:09

Alex Schenkel


People also ask

What is phaser3?

Phaser 3 is the new version of the Phaser Game Framework series. It includes a brand-new custom WebGL renderer designed specifically for the needs of modern 2D games. Phaser uses both a Canvas and WebGL renderer internally and automatically switch between them based on browser support.

How do you restart scenes in Phaser 3?

You can restart a scene by calling start on it this. scene. start() with no key given. It will stop the current scene, then start it again.


1 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;
}
like image 177
yolenoyer Avatar answered Oct 12 '22 22:10

yolenoyer