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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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
…)Even when a script does almost nothing it takes longer than 10 microseconds for each interval:
You start noticing a difference when a computer is slower or a browser is slower.
If you are making a game, the following gameloop minimizes the problem that it runs with different speed on different computers:
You have to keep in mind that your game logic
doGameMechanics()
and drawingdrawGame()
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 callsetTimeout
with 0 milliseconds as second parameter. This is needed so other Threads (like user input) get executed, because Javascript is single-threaded.