简体   繁体   English

在我的游戏中添加计时器

[英]Adding a timer to my game

I am currently working on a html5 canvas game. 我目前正在研究html5画布游戏。 I want to add a timer, so that you have a certain amount of time to collect as many items as possible in. I have tried a few ways of doing it, but due to my lack of skill and experience when it comes to javascript I have not yet made it work. 我想添加一个计时器,以便您有一定的时间来收集尽可能多的项目。我尝试了几种方法,但是由于我对javascript缺乏技巧和经验,尚未使其工作。 So my question is how to do this in an as simple as possible way? 所以我的问题是如何以尽可能简单的方式做到这一点?

My code: 我的代码:

Thanks in advance!! 提前致谢!!

requestAnimationFrame is a very efficient way of doing timers in the browser. requestAnimationFrame是在浏览器中执行计时器的一种非常有效的方法。

Some Benefits of requestAnimationFrame: requestAnimationFrame的一些好处:

  • automatically synchronizes canvas drawings with the current display refresh cycle, 自动将画布图形与当前的显示刷新周期同步,

  • multiple requestAnimationFrame calls are coordinated, 协调了多个requestAnimationFrame调用,

  • automatically suspends the loop if the user changes do a different browser tab 如果用户更改执行其他浏览器选项卡,则会自动暂停循环

  • each loop automatically receives a highly precise timestamp. 每个循环都会自动接收一个高度精确的时间戳。 Use this timestamp to determine when to trigger animation work (like your end-of-game) and/or to determine how much animation work to do. 使用此时间戳可以确定何时触发动画工作(例如游戏结束)和/或确定要执行多少动画工作。

Here's how to make it work: 使其运作的方法如下:

Create 1+ javascript objects. 创建1个以上的javascript对象。 Each object is one timer. 每个对象是一个计时器。

Each timer object defines some work that should be done after a specified delay. 每个计时器对象定义在指定的延迟后应完成的一些工作。

var timers=[];

timers.push({

    // this timer fires every 500ms
    delay:500,            

    // fire this timer when requestAnimationFrame's timestamp
    // reaches nextFireTime
    nextFireTime:0,        

    // What does this timer do?
    // It execute the 'doTimers' function when this timer fires
    doFunction:doTimers,  

    // just for testing: accumulate how many times this timer has fired
    counter:0

});

Create an animation loop with requestAnimationFrame 使用requestAnimationFrame创建动画循环

// the animation loop
// The loop automatically receives the currentTime
function timerLoop(currentTime){

    // schedule another frame 
    // this is required to make the loop continue
    // (without another requestAnimationFrame the loop stops)
    requestAnimationFrame(timerLoop);

    // iterate through each timer object
    for(var i=0;i<timers.length;i++){

        // if the currentTime > this timer's nextFireTime...
        // then do the work specified by this timer
        if(currentTime>timers[i].nextFireTime){           

            var t=timers[i];

            // increment nextFireTime
            t.nextFireTime=currentTime+t.delay;

            // do the work specified in this timer
            // This timer will call 'doFunction' & send arguments: t,i
            t.doFunction(t,i);
        }
    }        
}

Start the animation loop 开始动画循环

requestAnimationFrame(timerLoop);

Here's example code and a Demo: 这是示例代码和演示:

 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var timers=[]; timers.push({delay:50,nextFireTime:0,doFunction:doTimers,counter:0}); timers.push({delay:500,nextFireTime:0,doFunction:doTimers,counter:0}); timers.push({delay:5000,nextFireTime:0,doFunction:doTimers,counter:0}); requestAnimationFrame(timerLoop); function timerLoop(currentTime){ requestAnimationFrame(timerLoop); for(var i=0;i<timers.length;i++){ if(currentTime>timers[i].nextFireTime){ var t=timers[i]; t.nextFireTime=currentTime+t.delay; t.doFunction(t,i); } } } function doTimers(t,i){ ctx.clearRect(0,100+i*20-20,cw,20); ctx.fillText('Timer#'+i+' with '+t.delay+'ms delay has fired '+(++t.counter)+' times.',20,100+20*i); } 
 body{ background-color: ivory; padding:10px; } #canvas{border:1px solid red;} 
 <canvas id="canvas" width=300 height=300></canvas> 

When the game begins set a timer using the setTimeout() function. 游戏开始时,请使用setTimeout()函数设置一个计时器。

Since your game is currently running indefinitely I'd change the last bit of your code to give it an ending. 由于您的游戏当前正在无限期运行,因此我将更改代码的最后一部分以使其结束。

var time = Date.now();
var running = setInterval(run, 10); // Save this so we can clear/cancel it later

setTimeout(function() {        // Set a timer
  clearInterval(running);      // Stop the running loop
  alert('Game over!');         // Let the user know, do other stuff here
}, 30000);                     // time in miliseconds before the game ends

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM