所以我读了http://www.koonsolo.com/news/dewitters-gameloop/comment-page-2/#comments上的着名文章,该文章描述了实现游戏循环的不同方法。我试图实现Javascript文章中描述的最终方法(暂时忽略插值):
var Timer = {
pastTime : 0,
currentTime : 0,
started : false,
//starts the timer
start: function(){
if(!this.started){
this.started = true;
this.pastTime = new Date().getTime();
}
},
//gets the time in MILLSECONDS
getTime: function(){
return new Date().getTime() - this.pastTime;
},
//stops the timer but does not reset it (i.e. getTime() can still be
called to get the time between start() and end())
end: function(){
if(this.started){
this.currentTime = new Date().getTime();
this.started = false;
return this.currentTime - this.pastTime;
}
},
//resets the timer
reset: function(){
this.pastTime = 0;
this.currentTime = 0;
this.started = false;
}
var maxFrameSkip = 5;
var nextTick = new Date().getTime();
var TICKS_PER_SECOND = 25;
var tickTimeMillis = 1000 / TICKS_PER_SECOND;
var ticksPerSecondReal = 0;
var ticksCounter = 0;
var timer = Object.create(Timer);
var loops = 0;
function gameLoop(){
loops = 0;
timer.start();
while(new Date().getTime() > nextTick && loops < maxFrameSkip){
update();
ticksCounter++;
nextTick += tickTimeMillis;
loops++;
}
draw();
if(timer.getTime() >= 1000){
ticksPerSecondReal = ticksCounter;
ticksCounter = 0;
timer.reset();
}
console.log(ticksPerSecondReal);
window.requestAnimationFrame(gameLoop);
}
gameLoop();
所以我遇到的问题是console.log(ticksPerSecondReal)应该总是给我25,因为这是我想要和设置的每秒常数滴答。我最终获得的是一个25和26的交替数字。所以定期(约1秒)它将是25然后是26然后是25,依此类推。当它应该恒定在25时,它会不停地来回切换。这里有什么问题?