Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

2d-games

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 !

like image 829
Elfayer Avatar asked Dec 21 '22 06:12

Elfayer


2 Answers

Frame rate should have no effect on the game play what so ever. If its gettig 60FPS or 1000s of FPSs then that shouldn't effect anything.

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

So when you move the snake. It wants to move by a distance per frame. If the frame rate is low it will bigger distance than if the frame rate is high. The distance is the speed_it_moves_at * delta_time.

like image 91
Andrew Avatar answered Dec 24 '22 02:12

Andrew


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.

like image 34
meagar Avatar answered Dec 24 '22 02:12

meagar