[英]Adding a timer to my game
我目前正在研究html5画布游戏。 我想添加一个计时器,以便您有一定的时间来收集尽可能多的项目。我尝试了几种方法,但是由于我对javascript缺乏技巧和经验,尚未使其工作。 所以我的问题是如何以尽可能简单的方式做到这一点?
我的代码:
提前致谢!!
requestAnimationFrame
是在浏览器中执行计时器的一种非常有效的方法。
requestAnimationFrame的一些好处:
自动将画布图形与当前的显示刷新周期同步,
协调了多个requestAnimationFrame调用,
如果用户更改执行其他浏览器选项卡,则会自动暂停循环
每个循环都会自动接收一个高度精确的时间戳。 使用此时间戳可以确定何时触发动画工作(例如游戏结束)和/或确定要执行多少动画工作。
使其运作的方法如下:
创建1个以上的javascript对象。 每个对象是一个计时器。
每个计时器对象定义在指定的延迟后应完成的一些工作。
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
});
使用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);
}
}
}
开始动画循环
requestAnimationFrame(timerLoop);
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>
游戏开始时,请使用setTimeout()函数设置一个计时器。
由于您的游戏当前正在无限期运行,因此我将更改代码的最后一部分以使其结束。
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.