unity-game-engineframetimedeltarigid-bodies

Unity - In what cases should I add Time.deltaTime?


I'm new to Unity and I see many times that Time.deltaTime needs to be added. In which cases should I add it? I know this is so that there will be no excess power in the event of a quick refresh of the frame's computer.

For example, in the next case, do I need to add Time.deltaTime?

playerRigidbody.AddForce(Vector3.up * 100 * Time.deltaTime, ForceMode.Impulse);

Solution

  • Time.deltaTime is the amount of seconds it took for the engine to process the previous frame. It's calculation is rather simple: it uses the system's internal clock to compare the system time when the engine started processing the previous frame to the system time when the engine started processing the current frame. Every motherboard has a "system clock" which is responsible to keep track of time. Operating systems have access to that system clock and provide API's to read that clock. And Unity gets the time from that API and that's how things are synchronized.

    Think of a game as a movie, which is essentially a sequence of images. The difference is that a movie is rendered at a fixed rate of 24 images per second, while a game doesn't have a fixed frame rate.

    In a movie, if a car travels at 1 meter per second, each image will make it move by 1/24 meter, and after 24 images (1 second) the car will have traveled exactly 1 meter. It's easy because we know that each frame takes exactly 1/24 second.

    In a game, we have to do the same thing, except the frame rate varies. Some frames can take 1/60 second, some others can take 1/10 second. We can't use a fixed ratio. Instead of a fixed number we have to use Time.deltaTime. Each frame, the car will move a distance proportional to the time of the frame. After roughly 1 second, the car will have traveled roughly 1 meter

    Delta is the mathematical symbol for a finite difference. Its use is very common in english when talking about something that changed over time.

    deltaTime is a difference of time, so it's a Delta

    Shorter Terms

    You must always use Time.deltaTime when moving objects over time, either by supplying it yourself or by making use of functions like SmoothDamp that use Time.deltaTime by default (hardly any functions do that though). But you must never use Time.deltaTime for input that's already framerate-independent, such as mouse movement, since in that case using Time.deltaTime will do the opposite of what you intend.

    If you're ever unsure you can always toggle vsync on and off and observe any potential speed differences. If the game's already running close to the monitor refresh rate anyway, then make use of Application.targetFrameRate instead.