Answer the question
In order to leave comments, you need to log in
How to organize game loops?
Here the question of the organization of game cycles interests.
It would be desirable that updating of a condition, did not depend on updating of a picture. And updating the picture, it was desirable not to be fixed.
From good material, I found only such an article on Habré : Game cycles or ElectroCardioGama.
Answer the question
In order to leave comments, you need to log in
Updating the image in js is weighted by requestAnimationFrame .
Due to the single threaded nature of js instead of a loop
while(game_is_running){
update_game();
sleep(time);
}
var update = Date.now();
function f(){
var last = update;
update_game();
update = Date.now();
if(game_is_running) setTimeout(f, time - update + last);
}
f();
It would be desirable that updating of a condition, did not depend on updating of a picture. And updating the picture, it was desirable not to be fixed.
To Rock's comment - also do not forget that Javascript is not accurate in time, so the game should add the dependency of variables (cooldown, movement) to the number of elapsed milliseconds.
I don't know how things are with JS games, but in C++ the time since the last update is passed to the update function, usually in milliseconds. This time is convenient to take into account for moving the object.
void update(float dt)
{
float traveled = getSpeed() * dt + getTravaledDistance();
setTraveledDistance(traveled);
}
// main loop
while(!done)
{
float dt = getTimeSinceLastUpdate();
dt = min(33.3, dt); // equals 30 fps
update(dt);
render();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question