Skip to content Skip to sidebar Skip to footer

Why Speed Of My Game Character Is Different In Different Computers?

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 chara

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

Solution 2:

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

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

}
interval()

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

Solution 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 loopvar startTime, endTime, executionTime;

functiongameLoop(){

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

    if(executionTime < loopTime) { // we were faster than maximum allowed// sleep the remaining time so the game does not go too fastsetTimeout(function(){ gameLoop(); }, loopTime - executionTime);
    }else{ // we were slower than maximum allowedsetTimeout(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.

Post a Comment for "Why Speed Of My Game Character Is Different In Different Computers?"