我是 javascript/typescript 的新手,我正在尝试学习它,同时使用 Phaser 构建一个简单的游戏。我坚持启动游戏实例:当我像在 Phaser 网站上的第一个示例中那样创建它时,它会启动,但是如果我在调用表单提交的函数中创建游戏对象,它会启动但会立即结束;这是代码:
index.html
<form class="well" onsubmit="submitForm()">
...
...
<button type="submit" class="btn btn-primary">Play</button>
</form>
应用.ts
var game: SimpleGame;
function submitForm() {
console.log('Form submitted');
game = new SimpleGame();
}
游戏.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()
返回时游戏对象都被销毁。
最佳答案
问题是表单提交。如果您在所选浏览器中打开开发人员工具,您会看到该表单有效地 POST 回页面,导致刷新。
一种解决方案是更新 index.html 中的 form
元素,如下所示:
<form class="well" onsubmit="submitForm(); return false;">
// ...
<button type="submit" class="btn btn-primary">Play</button>
</form>
return false;
将阻止 POST。
如果您不需要表单来实际发布任何数据,您可以删除提交类型并在按钮本身上连接一个事件。
关于javascript - 启动 Phaser 游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525429/