Hadrien Delphin Hadrien Delphin - 1 year ago 64
TypeScript Question

Phaser Typescript function don't launch

I'm trying to make a little HTM5 game using Phaser.io.

I have a small issue that I can't fix.

In my MainClass (the game), I just want to create a loop that will create a new object (a coin) and add it to a group.

But I don't know why, the little function I call never launch.

Here's my code :

create() {

//coins group
this.coins = this.game.add.group;

//set background
this.game.stage.backgroundColor = "#00F6FA";
//load the map
this.map = this.game.add.tilemap('level', 195, 195, 2, 4);
this.map.addTilesetImage('free-2d-game-tiles-post-pic-1', 'tiles');
//load collision layer
this.layer = this.map.createLayer('collision');
//this.layer.debug = true;
//make the layer collide
this.map.setCollisionBetween(8, 9, true, this.layer.index, true);
//enable physics
//set the player
this.player = new Player(this.game, 0, 0);

this.game.time.events.repeat(Phaser.Timer.SECOND * 2, 10, this.createCoin, this);

And just behind :

createCoin(): void {

generate a coin



Pretty simple,but nothing never happen.

Do you see what I miss?


ok here's my code on Github :


I still don't know what's wrong...

Answer Source

Few thigs. First, we need whole code: how do you create the game and how do you apply create function to it? Second, this is dynamiccaly binded. To bind it to your object, you may for example use fat arrow syntax: createCoin = () => { ... }. Look at your this (console.log(this) in create method) - this is not what you expect it to be :)

Take a look at working example:

export default class SimpleGame {
    private game;

    constructor() {
        this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { create: this.create });

    //Used by Phaser to create real game - prepare it. Use fat arrow syntax here!
    create = () => {

    //This is ok to make it as normal method, as only bounded this ( create) use it
    private someInternalMethod(){

Take a look at my source code (simple game in TS & Phaser) for more: https://github.com/Ami777/AmyInSpace

More about fat arrow in TS: https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

More about this syntax in ES6: https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/ .

Regards, Jakub Król.