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?
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With