Jump to content

Why my `phaser_game` is `undefined` here?


notalentgeek
 Share

Recommended Posts

const ASSETS:string = "./assets";

// Simple game.
class SimpleGame {
  phaser_game:Phaser.Game;

  constructor () {
    this.phaser_game = new Phaser.Game(
      800,
      600,
      Phaser.AUTO,
      "phaser",
      { create: this.create, preload: this.preload }
    );
  }

  create () {
    let piplup_sprite:Phaser.Sprite = this.phaser_game.add.sprite(
      this.phaser_game.world.centerX,
      this.phaser_game.world.centerY,
      "logo"
    );
    piplup_sprite.anchor.setTo(0.5, 0.5);
  }

  preload () {
    let piplup_sprite_path:string = ASSETS + "/piplup.png";

    console.log(this.phaser_game); // Undefined?

    this.phaser_game.load.image("logo", piplup_sprite_path);
  }
}

window.onload = () => {
  let simple_game:SimpleGame = new SimpleGame();
};

I suppose the title is self-explanatory. I used Phaser with vanilla JavaScript before. Decided to learn TS but I got stuck why the `this.phaser_game` is undefined, while it is clearly defined in `constructor`?

Link to comment
Share on other sites

If I change the variable name from `phaser_game` to `game` it works. Is this true? Why the variable name need to be dictated by Phaser if so?

Here is the working codes.

const ASSETS:string = "./assets";

// Simple game.
class SimpleGame {
  game:Phaser.Game;

  constructor () {
    this.game = new Phaser.Game(
      800,
      600,
      Phaser.AUTO,
      "phaser",
      { create: this.create, preload: this.preload }
    );
  }

  create () {
    let piplup_sprite:Phaser.Sprite = this.game.add.sprite(
      this.game.world.centerX,
      this.game.world.centerY,
      "piplup"
    );
    piplup_sprite.anchor.setTo(0.5, 0.5);
  }

  preload () {
    let piplup_sprite_path:string = ASSETS + "/piplup.png";

    console.log(this.game); // Undefined?

    this.game.load.image("piplup", piplup_sprite_path);
  }
}

window.onload = () => {
  let simple_game:SimpleGame = new SimpleGame();
};

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...