如何在游戏中添加计时器?

How do I add a timer to my game?

本文关键字:添加 计时器 游戏      更新时间:2023-09-26

我正在制作一款平台游戏,当玩家收集到所有金币后,他们将进入下一关,我该如何在屏幕上添加计时器,当它到达0时,关卡将重新开始?这是我现在的代码部分,处理玩家是否在接触熔岩时重新开始关卡。

Level.prototype.playerTouched = function(type, actor) {
  if (type == "lava" && this.status == null) {
    this.status = "lost";
    this.finishDelay = 1;
  } else if (type == "coin") {
    this.actors = this.actors.filter(function(other) {
      return other != actor;
    });
    if (!this.actors.some(function(actor) {
           return actor.type == "coin";
         })) {
      this.status = "won";
      this.finishDelay = 1;
    }
  }
};
function runGame(plans, Display) {
  function startLevel(n) {
    runLevel(new Level(plans[n]), Display, function(status) {
      if (status == "lost")
        startLevel(n);
      else if (n < plans.length - 1)
        startLevel(n + 1);
      else
        console.log("You win!");
    });
  }
  startLevel(0);
}

一种选择是使用setInterval

下面是来自http://www.w3schools.com/js/js_timing.asp

的示例代码
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>

使用这个示例,您可以创建一个剩余时间的变量,并减少每次调用计时器。

像这样:

var myVar = setInterval(myTimer, 1000);
var timeLeft = 10;
function myTimer() {
    if (timeLeft > 0){
         timeLeft = timeLeft - 1;
         document.getElementById("demo").innerHTML = timeLeft;    
    }else{
         document.getElementById("demo").innerHTML = "Game over";    
     }
}