I would like to know what is the best way to modify a value over time to be sure that the result will be the same even if the game run slower or faster at some point.
So I’m doing this in the update function:
// value that will approximately reach 1.0f when the game is running at normal framerate
float deltaTime = Time.deltaTime * 33.3f;
speed *= 0.92f * deltaTime;
But I get some unexpected result sometimes and I don’t understand why. Anyone can tell me which is the best way to go?
With your calculation you expect to have a constant framerate of 30 since you say “it will approx. reach 1.0f”.
But that wouldn’t be consistent unless you try to set the target fps to 30, which doesn’t mean it will exactly hit it.
Also, whatever you want to move with that speed, it’ll move approx. ~ 30.6 units per second.
After all I’m not sure what you’re trying to do.
Do not rely on the assumption that you get a consistent value when you calculate X = constant * Time.delta, because that would basically mean you expect time.deltaTime to be consistent, which leads to the above…
You didn’t really say what you expected to happen, only that you get unexpected results. So i provided basic knowledge that might help you to find it. Wasn’t meant to be a solution, as a solution can only be given if you provide enough information about the actual problem.
If you have good reasons to want it to be exactly the same, down to the very last bit (for example, using a lockstep simulation for multiplayer, or for saving efficient replay files), use FixedUpdate(), or some manually devised system that works similarly. FixedUpdate() lets you behave as if each iteration lasts exactly the same duration of time, even though they don’t in reality, because you are guaranteed to get exactly the number of expected updates over a sufficiently long span of time. (Well, this is guaranteed as long as your FixedUpdate() logic executes quickly enough; otherwise you get a dreaded spiral of death.)
And if you are cross-platform, favor integers (or fixed point values implemented on top of integers) rather than floats, because trying to get to-the-bit equality with floats cross-platform is scary. Heck, under some circumstances, it can be troublesome even on a single machine, since other programs or even libraries packaged with your own program can mess with the CPU’s floating point calculation settings.
I thought the OP meant how to change a value over time consistently and not how to check for equality, but yes FixedUpdate or something else might be better for deterministic calculations.