Best way for simple game-loop in Javascript?

2020-02-19 04:56发布

Is there a simple way to make a game loop in JavaScript? something like...

onTimerTick() {
  // update game state
}

8条回答
▲ chillily
2楼-- · 2020-02-19 05:28

Would this do?

setInterval(updateGameState, 1000 / 25);

Where 25 is your desired FPS. You could also put there the amount of milliseconds between frames, which at 25 fps would be 40ms (1000 / 25 = 40).

查看更多
甜甜的少女心
3楼-- · 2020-02-19 05:28

not sure how well this will work, but here is one method that uses a while loop and sleeps the thread. This is just an example, you can replace the game loop below with a better one, based on how you would do it in any other language. You can also find a better while loop here

let gameRunning = false;

async function runGameThread(){
    if(!gameRunning){
        gameRunning = true;

        // this function allows the thread to sleep (found this a long time ago on an old stack overflow post)
        const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

        // the game loop
        while(gameRunning){
            let start = new Date().getTime();
            gameUpdate();
            await sleep(start + 20 - new Date().getTime());
        }

    }
}

function stopGameThread(){
    while(gameRunning){
        try{
            gameRunning = false;
        }catch(e){}
    }
}

function gameUpdate(){
    // do stuff...
}
查看更多
登录 后发表回答