Why speed of my game character is different in dif

2019-02-28 15:21发布

问题:

I am developing an online game using Java Script. I am using setInterval (movimage, 10) method to move the game character. But I have seen that the movement speed of the game character is not same is all computer. Please suggest me.

回答1:

Instead of setInterval you should probably use requestAnimationFrame (https://developer.mozilla.org/en-US/docs/DOM/window.requestAnimationFrame).

There is no point trying to update something quicker than the screen can draw. You are aiming for 60fps, which is about 16ms per frame.

http://paulirish.com/2011/requestanimationframe-for-smart-animating/ has some more info about how to do this.

Browser support is pretty good (http://caniuse.com/#feat=requestanimationframe) in short, all current browsers apart from the Android Stock browser.

If you must have this working in IE9 and lower, https://gist.github.com/paulirish/1579671 does a decent job of simulating the behaviour in those browsers. (though to be honest, I suspect this will be the last of your worries, particularly in regard to the lack of canvas…)



回答2:

Even when a script does almost nothing it takes longer than 10 microseconds for each interval:

function interval(){
 var i=0
 intervalID= setInterval(function(){
   console.log("called",new Date().getTime());
   i++;
   if(i>=10){
     clearInterval(intervalID);
   }
 },10);

}
interval()

You start noticing a difference when a computer is slower or a browser is slower.



回答3:

If you are making a game, the following gameloop minimizes the problem that it runs with different speed on different computers:

var loopTime = 33; // 1000ms / 30fps (what we want) = 33ms per loop
var startTime, endTime, executionTime;

function gameLoop(){

    startTime = new Date().getTime();
    doGameMechanics();
    drawGame();
    endTime = new Date().getTime();
    executionTime = endTime - startTime;

    if(executionTime < loopTime) { // we were faster than maximum allowed
        // sleep the remaining time so the game does not go too fast
        setTimeout(function(){ gameLoop(); }, loopTime - executionTime);
    }else{ // we were slower than maximum allowed
        setTimeout(function(){ gameLoop(); }, 0);
    }
}

You have to keep in mind that your game logic doGameMechanics() and drawing drawGame() take some time, too. This can result in slower and faster game behaviour on different computers.

In this gameloop, we check how fast they were executed. After measuring the time, we know how long we have to wait (using setTimeout). If we were "too slow", we call setTimeout with 0 milliseconds as second parameter. This is needed so other Threads (like user input) get executed, because Javascript is single-threaded.