2

如果游戏以 177FPS 或 22FPS 运行,玩家的移动是如何计算的?我正在尝试在 Javascript 中执行此操作:

setInterval(update, 0);

function update() {
     player_x++;
}

问题预览

问题是播放器是否会根据帧速率移动得更快/更慢。我将如何解决这个问题?

4

3 回答 3

2

我强烈建议在可用时使用requestAnimationFrame(这将使您在现代浏览器中获得最佳帧速率),而在不可用时使用 setTimeout。然后根据动画开始后的时间确定您的玩家位置:

// Anonymous function used to make variables declared inside it not global
// This avoids conflicts in case variables with the same names are used
// in other scripts
(function(){

    // This checks for the requestAnimationFrame in each browser and store the first
    // it finds into requestAnimationFrame. If none are found it uses setTimeout
    // Attempting 60 frames per second.
    // It's taken from Paul Irish's blog: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    // and you can use it as is
    var requestAnimationFrame = (function(){
        return window.requestAnimationFrame    || 
               window.webkitRequestAnimationFrame || 
               window.mozRequestAnimationFrame    || 
               window.oRequestAnimationFrame      || 
               window.msRequestAnimationFrame     || 
               function(callback){
                   setTimeout(function(){ callback((new Date).getTime()); }, 1000/60);
               };
    })();

    var speed = 60; // pixels per second

    // This is used so that we only divide by 1000 once instead of every frame
    var calc = speed/1000;

    // Store the current time in start_time
    var start_time = (new Date).getTime();

    // This function is self invoking. It is wrapped in parenthesis and called immediately
    // time is passed in by requestAnimationFrame
    (function draw(time){
        // Calculate the new x position based on the current time
        var pos = (time - start_time)*calc;

        // Update the player's position
        // In my JSFiddle I update the style.left of a div
        player_x = pos;

        // Now that this frame is done request another frame.
        // draw will be called again before that frame is rendered
        requestAnimationFrame(draw);
    })();

})();

JSFiddle

于 2012-06-02T19:22:35.900 回答
1

尝试使用计时器功能,以便玩家根据时间移动而不是帧变化......

于 2012-06-02T19:17:11.523 回答
1

距离等于速度(常数)和时间。根据帧速率(以赫兹为单位),时间 t =1 / framerate会有所不同。

将其放入代码中:测量后续帧之间的时间并使用该时间来计算距离。

有时一个更好的主意是拥有一个后台线程(在 JavaScript 中,您可以setInterval()按照建议使用CezarisLT并使用常量时间。但是在实践中,您仍然需要测量后续调用之间的时间,因为setInterval()不能保证准确地在预定时间运行(长时间运行功能,高 CPU 使用率)。

顺便说一句,您的代码过于冗长,无法编译:

setInterval(update, 0)

function update() {
     player_x++;
}
于 2012-06-02T19:21:13.237 回答