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

I have already made several video games in C (a small personal project). And the problem I came across every time is the same as managing the cycles in the game.

For example, I encoded a snake in SFML. I processed cycles with a frame rate of 5 frames in normal mode, and when I turned on the power I changed it to 10. This works. But this is disgusting. And it does not work well with a bad computer. In the same idea, I also made a game where I decided that the cycle is equal to the rotation of the cycle (with an infinite cycle). The same problem, a high-performance computer will run faster than a low one.

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

Thanks in advance!

+4
source share
2 answers

In very broad terms, you need to simulate the state of the game so that it can "advance" with a given time step, and then, during each cycle of your main cycle, determine how much time has passed (usually a small fraction of a second) and advance the game the condition is only so much. This is how games look uninterrupted, regardless of frame rate.

The interval basically becomes a scaling factor for all movements. For example, if your snake moves forward with 5 units of distance per second, and during your main cycle you find that 0.01 seconds have passed since the last break of the snake, you must advance your snake (0.01 * 5) by the unit distance in this cycle .

+5
source

The frame rate should not affect the game, which is always so. If its gettig 60FPS or 1000s FPS, then this should not affect anything.

What you want to do is look at the delta time or elapsed time, if that is enough, then do a simulation or turn on the power.

So when you move the snake. He wants to move a distance per frame. If the frame rate is low, it will be a greater distance than with a high frame rate. Distance speed_it_moves_at * delta_time .

+6
source

Source: https://habr.com/ru/post/1479928/


All Articles