A
A
Alexander Shpak2014-02-06 13:43:58
JavaScript
Alexander Shpak, 2014-02-06 13:43:58

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

4 answer(s)
D
Denis Pushkarev, 2014-02-06
@rock

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);
}

to update the model, we use adjusted timers, something in the style
var update = Date.now();
function f(){
  var last = update;
  update_game();
  update = Date.now();
  if(game_is_running) setTimeout(f, time - update + last);
}
f();

A
Andrey Vershinin, 2014-02-06
@WolfdalE

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.

So the article talks about this after all (by the way, thanks for the article).
If you are interested in the implementation on a specific platform, then this is a fairly general question, depending on which part of the cycle it specifically concerns:
1) Well, in terms of the state, I think not, because it's all about the language.
2) If in terms of rendering - it already depends only on the platform, and the graphic libraries available for it.

N
Nadoedalo, 2014-02-06
@Nadoedalo

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.

T
Teivaz, 2014-02-16
@Teivaz

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);
}

At the same time, the drawing function and the update function are executed in the same thread (otherwise, you will need to synchronize threads, lock some methods, etc.).
And if the game suddenly freezes, then a rather large amount of time can come into the update and then the game elements can make a sharp jump. To get rid of this, you can trim the maximum possible time in the main loop:
// 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 question

Ask a Question

731 491 924 answers to any question