启动 Phaser 游戏

Launch Phaser game

我是 javascript/typescript 的新手,我正在尝试学习它,同时使用 Phaser 构建一个简单的游戏。我坚持启动游戏实例:当我像在 Phaser 网站上的第一个示例中那样创建它时,它会启动,但是如果我在调用表单提交的函数中创建游戏对象,它会启动但会立即结束;这是代码:

index.html

<form class="well" onsubmit="submitForm()">
    ...
    ...
    <button type="submit" class="btn btn-primary">Play</button>
</form>

app.ts

var game: SimpleGame;

function submitForm() {
    console.log('Form submitted');
    game = new SimpleGame();
}

game.ts

class SimpleGame {

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

这就像每次函数 submitForm() returns.

游戏对象被销毁一样

问题出在表单提交上。如果您在您选择的浏览器中打开开发人员工具,您会看到该表单有效地 POST 返回页面,导致刷新。

一个解决方案是更新 index.html 中的 form 元素,如下所示:

<form class="well" onsubmit="submitForm(); return false;">
    // ...
    <button type="submit" class="btn btn-primary">Play</button>
</form>

return false; 将阻止 POST。

如果您实际上不需要表单 POST 任何数据,您可以删除提交类型并在按钮本身上连接一个事件。