游戏状态
作为一种代码风格,也为了帮你模块你的代码,我推荐在游戏循环里像这样组织你的代码:
//Set the game statestate = play;//Start the game loopapp.ticker.add(delta => gameLoop(delta));function gameLoop(delta){//Update the current game state:state(delta);}function play(delta) {//Move the cat 1 pixel to the right each framecat.vx = 1cat.x += cat.vx;}
你会看到gameLoop每秒60次调用了state函数。state函数是什么呢?它被赋值为 play。意味着play函数会每秒运行60次。
下面的代码告诉你如何用这个新模式来重构上一个例子的代码:
//Define any variables that are used in more than one functionlet cat, state;function setup() {//Create the `cat` spritecat = new Sprite(resources["images/cat.png"].texture);cat.y = 96;cat.vx = 0;cat.vy = 0;app.stage.addChild(cat);//Set the game statestate = play;//Start the game loopapp.ticker.add(delta => gameLoop(delta));}function gameLoop(delta){//Update the current game state:state(delta);}function play(delta) {//Move the cat 1 pixel to the right each framecat.vx = 1cat.x += cat.vx;}
是的,我知道这有点儿 head-swirler! 但是,不要害怕,花几分钟在脑海中想一遍这些函数是如何联系在一起的。正如你将在下面看到的,结构化你的游戏循环代码,会使得切换游戏场景和关卡这种操作变得更简单。
