I have an app written in QT that uses QTimer. It's basically a game and all the actions are controlled by the timer. Game includes the ability to increase\decrease the game speed. The code for increasing the speed is
timerValue -= speedUpValue;
if (timerValue < maxSpeed) {
timerValue = maxSpeed;
}
timer -> setInterval(timerValue);
speedUpValue
and maxSpeed
are constants. Almost the same code is used for decreasing the speed. The problem is that setInterval
resets the internal timer and therefore if you keep rapidly increasing or decreasing the speed game eventually never proceeds because remainingTime
is constantly being reset. Is there a way to set remainingTime
manually or change the interval without resetting it?
You can omit the timer object altogether, and instead use the static method QTimer::singleShot(...)
, and set a new single shot on every timer event with the timerValue
. So no matter how frequently timerValue
is modified, each timer cycle will be completed with the old value and scheduled with the current value.
As RA mentioned, you can effectively achieve the same thing keeping the timer object, but moving the setInterval()
to the timer event, basically the same thing as above, but keeping the timer object, if you need it for some reason.
As Craig mentioned in the comments, the first approach will also ensure timer events don't get accumulated, in case your game logic takes longer. Also, if you go for an asynchronous design, it is possible that the next game cycle will begin execution before the old one is completed if you go for a continuously running timer.
It this regard, it is best to not use a continuously running timer, but schedule each next game cycle manually, and only if you need to. For example, you may not need to schedule another if the game comes to an end. Also, this will allow for finer control over how accurate the game speed goes, after the game cycle execution is completed, you can calculate how much time remains until the next one is needed, and schedule it with that value, or if the execution took too long, you can schedule it immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With