你可以用一百万种方式做到这一点。然而,您感觉最舒服,您的工程师也感觉最自信。
如果您正在寻找灵感或代码示例,这是我的一种方法。我有一个函数可以重复绘制菜单,直到按下按钮为止。按下按钮时,游戏将加载,旧的菜单单击事件侦听器将被删除,并添加新的游戏单击事件侦听器。我还结束了菜单的旧绘制循环并开始新的游戏绘制循环。以下是一些精选的片段,可让您了解其完成方式:
Game.prototype.loadMenu = function() {
var game = this;
var can = this.canvas;
// now we can use the mouse for the menu
can.addEventListener('click', game.menuClickEvent, false);
can.addEventListener('touchstart', game.menuClickEvent, false);
// draw menu
this.loop = setInterval(function() { game.drawMenu() }, 30);
};
Game.prototype.drawMenu = function() {
// ... draw the menu
}
Game.prototype.loadLevel = function(levelstring) {
// unload menu
var can = this.canvas;
var game = this;
can.removeEventListener('click', game.menuClickEvent, false);
can.removeEventListener('touchstart', game.menuClickEvent, false);
if (this.loop) clearInterval(this.loop);
// ... other level init stuff
// now we can press keys for the game
//can.addEventListener('click', game.gameClickEvent, false);
can.addEventListener('touchstart', game.gameClickEvent, false);
can.addEventListener('keydown', game.gameKeyDownEvent, false);
this.loop = setInterval(function() { game.tick() }, 30);
}
// called from tick()
Game.prototype.draw = function(advanceFrame) {
// ...
}
这样我就能够将游戏绘图和游戏事件与菜单绘图和菜单事件分开。如果我想让它们看起来真正漂亮的话,它还给了我在菜单中使用游戏/动画元素的余地。
(我也在双胞胎游戏开发讨论中发布了这个)