简体   繁体   中英

Synchronize simulation time with real time

I'm doing a simulation. It must be consistent from machine to machine, so I'm not using Time.deltaTime , but using a fixed value to represent the frame duration (say 0.002s).

The problem is: though the simulation is consistent, irregularities in the durations of the frames of the game make it look like in a long frame it moves X and in a short frame it also moves X, making it look wierd from time to time.

The question: is there a way to synchronize real time with simulation time without losing simulation precision?

Time.deltatime tells us how much time has passed since the last frame.

From Unity documentation :

This property provides the time between the current and previous frame.

If you wait a fixed time between frames, the framerate will affect your simulation time.

If you want to do something in the game world every 1 second in the real world, you need to use Time.deltatime. You keep track of how much time has passed by adding Time.deltatime to a variable and check if it is equal to or more than wanted time.

private float timer = 0.0f;
private float waitTime = 1.0f;

void Update() {
    timer += Time.deltatime;
    if (timer >= waitTime) {
        timer = 0.0f;
        doStuff();
    }
}

Instead of using Time.deltatime you may want to use Unity's Fixedupdate . You use it just like you'd use Update() but instead of firing every frame, it fires it on a fixed interval. Default is 0.02s and you can change it from Edit > Settings > Time > Fixed Timestep. This is used for physics calculations.

I hope this answered your question and/or helped you with your problem. If there is something I missed let me know and I'll try to give a better answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM