Hadrien Delphin Hadrien Delphin - 3 months ago 20
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
this.game.physics.startSystem(Phaser.Physics.ARCADE);
//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

*/
console.log('test');

}


Pretty simple,but nothing never happen.

Do you see what I miss?

EDIT 1:

ok here's my code on Github :

https://github.com/c4n4r/coinFall/blob/master/JS/app.ts

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

Answer

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.someInternalMethod();
    }

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

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.

Comments