Search code examples
c++c2d-games

C / C++ - How to manage the cycles in a video game?


I have already made some video games in C (small personal project). And the problem I encountered every time is the same, how to manage the cycles in a game.

For example, I coded a snake in SFML. I handled the cycles with the frame rates: 5 frame rates while normal, and with a power up, I changed it to 10. That works. But it's hideous. And it won't work correctly with a bad computer. In the same idea, I also made a game where I decided that a cycle was equal to a turn of a loop (with an infinite loop). Same problem, a high performance computer will go faster than a low one.

So, can someone advice me on how to manage correctly and properly cycles in a video game.

Thanks in advance !


Solution

  • In very broad terms, you need to model your game state such that it can "advance" by a given increment of time, and then, during each cycle of your main loop, determine how much time has elapsed (typically a small fraction of a second) and advance the game state by only that much. This is how games appear to work smoothly regardless of frame rate.

    The interval basically becomes a scaling factor on all movement. For example, if your snake is moving forward at 5 units of distance per second, and during your main loop you find that 0.01 seconds have elapsed since the last time the snake moved, you would advance your snake by (0.01 * 5) unit of distance during that loop.