为了代码模块化,我建议你像这样构建你的游戏循环:

//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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

您可以看到gameLoop每秒调用60次state函数,这意味play方法每秒执行60次。

下面是重构上面那个案例后的代码:

//Define any variables that are used in more than one function
let 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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

是的,我知道,这有点让人头晕!但是,不要让它吓到你,花一两分钟在你的脑海中回想一下这些功能是如何联系在一起的。正如你将看到的,像这样构建你的游戏循环,将会让你更容易去处理游戏场景和关卡的切换。

lastUpdate: 2/3/2023, 2:34:54 AM