Why speed of my game character is different in dif

2019-02-28 15:10发布

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.

3条回答
甜甜的少女心
2楼-- · 2019-02-28 15:27

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…)

查看更多
Luminary・发光体
3楼-- · 2019-02-28 15:38

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.

查看更多
Root(大扎)
4楼-- · 2019-02-28 15:39

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.

查看更多
登录 后发表回答