Shivo
Shivo

Reputation: 43

C++ Run only for a certain time

I'm writing a little game in c++ atm.

My Game While loop is always active, in this loop, I have a condition if the player is shooting.

Now I face the following problem,

After every shot fired, there is a delay, this delay changes over time and while the delay the player should move.

atm I'm using Sleep(700) the problem is I can't move while the 700 ms, I need something like a timer, so the move command is only executed for 700 ms instead of waiting 700 ms

Upvotes: 1

Views: 1048

Answers (1)

Water
Water

Reputation: 3715

This depends on how your hypothetical 'sleep' is implemented. There's a few things you should know, as it can be solved in a few ways.

You don't want to put your thread to sleep because then everything halts, which is not what you want.

Plus you may get more time than sleep allows. For example, if you sleep for 700ms you may get more than that, which means if you depend on accurate times you will get burned possibly by this.

1) The first way would be to record the raw time inside of the player. This is not the best approach but it'd work for a simple toy program and record the result of std::chrono::high_resolution_clock::now() (check #include <chrono> or see here) inside the class at the time you fire. To check if you can fire again, just compare the value you stored to ...::now() and see if 700ms has elapsed. You will have to read the documentation to work with it in milliseconds.

2) A better way would be to give your game a pulse via something called 'game ticks', which is the pulse to which your world moves forward. Then you can store the gametick that you fired on and do something similar to the above paragraph (except now you are just checking if currentGametick > lastFiredGametick + gametickUntilFiring).

For the gametick idea, you would make sure you do gametick++ every X milliseconds, and then run your world. A common value is somewhere between 10ms and 50ms.

Your game loop would then look like

while (!exit) {
    readInput();

    if (ticker.shouldTick()) {
         ticker.tick();
         world.tick(ticker.gametick); 
    }

    render();
}

The above has the following advantages:

  • You only update the world every gametick

  • You keep rendering between gameticks, so you can have smooth animations since you will be rendering at a very high framerate

  • If you want to halt, just spin in a while loop until the amount of time has elapsed

Now this has avoided a significant amount of discussion, of which you should definitely read this if you are thinking of going the gametick route.


With whatever route you take, you probably need to read this.

Upvotes: 1

Related Questions