游戏状态
作为一种代码风格,也为了帮你模块你的代码,我推荐在游戏循环里像这样组织你的代码:
//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 frame cat.vx = 1 cat.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` sprite cat = new Sprite(resources["images/cat.png"].texture); cat.y = 96; cat.vx = 0; cat.vy = 0; app.stage.addChild(cat); //Set the game state state = play; //Start the game loop app.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 frame cat.vx = 1 cat.x += cat.vx;}
head-swirler! 但是,不要害怕,花几分钟在脑海中想一遍这些函数是如何联系在一起的。正如你将在下面看到的,结构化你的游戏循环代码,会使得切换游戏场景和关卡这种操作变得更简单。
