在写游戏的时候,动画移动的速度需要保持一致,为了在各个软硬件环境中速度的一致,需要考虑帧频的不同。
计算时间系数:
时间系数 = 目标FPS / 实际FPS
计算实际FPS
actualFPS = 1000 / (endTime - startTime)
代码逻辑执行前计算开始的时间,执行完代码逻辑后的时间(结束时间)
创建一个timeInfo对象,接收一个参数goalFPS(想要达到的目标FPS),如果达不到,将调整移动速度使其看起来达到了goalFPS。
/** * elapsed //经过的时间 * coeff //时间系数 * FPS //实际FPS * averageFPS //平均FPS **/ var timeInfo = function (goalFPS) { var oldTime, paused = true, iterCount = 0, totalFPS = 0; return { getInfo: function () { if(paused === true) { paused = false; oldTime = +new Date(); return {elapsed:0, coeff:0, FPS:0, averageFPS:0 }; } var newTime = +new Date(); var elapsed = newTime - oldTime; var FPS = 1000/elapsed; oldTime = newTime; iterCount ++; totalFPS += FPS; return { elapsed: elapsed, coeff: goalFPS / FPS, FPS: FPS, averageFPS: totalFPS / iterCount }; }, pause: function() {paused = true;} }; }; //use /* var timer = timeInfo(40); //... animate start setTimeout setInterval var timeData = timer.getInfo(), elapsed = timeData.elapsed, Coefficient = timeData.coeff, FPS = timeData.FPS, averageFPS = timeData.averageFPS; //... animate end */
时间: 2024-11-11 01:33:58