Phaser Typescript 功能无法启动

Phaser Typescript function don't launch

我正在尝试使用 Phaser.io 制作一个 HTM5 小游戏。

我有一个小问题无法解决。

在我的 MainClass(游戏)中,我只想创建一个循环来创建一个新对象(一枚硬币)并将其添加到一个组中。

但是我不知道为什么,我调用的那个小函数永远不会启动。

这是我的代码:

  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);
}

紧随其后:

    createCoin(): void {
    /*

    generate a coin

    */
    console.log('test');

}

很简单,但什么都没有发生。

你看到我想念的了吗?

编辑 1:

好的,这是我在 Github 上的代码:

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

我还是不知道怎么了...

小东西。首先,我们需要完整的代码:如何创建游戏以及如何应用创建函数? 其次,this 是动态绑定的。要将它绑定到您的对象,您可以使用粗箭头语法:createCoin = () => { ... }。 查看您的 this(创建方法中的 console.log(this))- 这不是您期望的 :)

看看工作示例:

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!
    }
}

查看我的源代码(TS & Phaser 中的简单游戏)了解更多信息:https://github.com/Ami777/AmyInSpace

更多关于 TS 中的粗箭头:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

关于 ES6 语法的更多信息:https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/ .

此致,Jakub Król。

实际上我建议使用 Phaser.State,我认为这会让事情变得更容易一些。然后你可以在 TypeScript 中使用 extends 关键字,像这样:

class SimpleGame extends Phaser.State {

    // define your properties for SimpleGame
    coins: Phaser.Group;
    //game: Phaser.Game; // <- not needed! SimpleGame extends Phaser.State
    map: Phaser.Tilemap;
    // etc

    // define methods for SimpleGame
    create() {
        //.. create code here
        this.coins = this.add.group();

        // 'this' extends type Phaser.State, so notice you can use this.time:
        this.time.events.repeat(Phaser.Timer.SECOND * 2, 10, this.createCoin, this);
    }

    update() {
        //.. update code here
    }

    createCoin() {
        //.. create a coin
        var newCoin = new Banana(this, this.world.randomX, 0)
        this.coins.add(newCoin)
    }
}