15

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?

James Skemp
  • 8,018
  • 9
  • 64
  • 107
Alex Schenkel
  • 728
  • 1
  • 7
  • 13

4 Answers4

17

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;
}
yolenoyer
  • 8,797
  • 2
  • 27
  • 61
13

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.

James Skemp
  • 8,018
  • 9
  • 64
  • 107
  • Will an image placed on `this.cameras.main.centerX` and `Y` move with camera? What if I want it to be static and not to move with camera, instead being a background of the scene? – VELFR Jun 09 '19 at 12:57
  • @VELFR it depends upon your logic. If you put the above in your `update()` then the image position will be updated every frame, but if you put it in `create()` then it will take the current camera's values and not move the image. – James Skemp Jun 10 '19 at 13:12
2

The following should work:

scene.sys.game.scale.gameSize
Tyler Liu
  • 19,552
  • 11
  • 100
  • 84
2

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
Shutt
  • 31
  • 2