为什么要在游戏循环中使用while循环?

问题描述 投票:-1回答:1

只是想知道,是否有特定的原因将while循环用作游戏循环。或者我可以使用另一种方法,例如这种方法。

注意:这不是正确的代码,尚未经过测试。这只是一个总的想法。这个示例也与特定的编码语言不一致,但是可能大多数情况下都遵循JavaScript,因为这是我最想知道的编码语言。我实际上已经在dart(Google扑打)中尝试过类似的操作。

var startTime;
var running = false;

function loop1(){
  startTime = system.currentMillis();
  loop2();
}

loop2(){
  gameUpdate();
  //ignore my math, I did not focus on doing that property
  //this is just an example and is not proper math
  var delay = 1000 / (system.currentMillis() - startTime);
  setTimeout(loop3, delay);
}

loop3(){
  if(running){
    loop1();
  }
}

编辑:使用类似的方法来避免需要使用sleep();会对性能有所帮助吗? (或手机电池)

javascript game-loop
1个回答
1
投票

完全有可能将您的代码用作主要游戏循环。首选while的原因是,主游戏循环会无限执行直到中止,这可以简单地通过while (true)并通过break或在while (abort == false)并将内部的abort = true设置在内部的某个位置来中止。请注意,其他循环变量,例如fordo-while更冗长,除非您的语言让您执行for (;;)。还请注意,您可以使用while循环将提议的循环重组为更简单的版本。

© www.soinside.com 2019 - 2024. All rights reserved.