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

时间:2016-11-07 21:04:51

标签: javascript

我正在制作一个平台游戏,当玩家收集所有硬币时,他们会进入下一关,我如何在屏幕上添加一个计时器,当它达到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);
}

1 个答案:

答案 0 :(得分: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";    
     }

}