Что такое time deltatime

Understanding Time.deltaTime

Что такое time deltatime. Смотреть фото Что такое time deltatime. Смотреть картинку Что такое time deltatime. Картинка про Что такое time deltatime. Фото Что такое time deltatime

Что такое time deltatime. Смотреть фото Что такое time deltatime. Смотреть картинку Что такое time deltatime. Картинка про Что такое time deltatime. Фото Что такое time deltatime

Most of the people (including me) who start with Unity are having a problem with learning Time.deltaTime. To understand how it works, firstly, I will explain its definition. Then I will show a step-by-step example.

By definition, Time.deltaTime is the completion time in seconds since the last frame. This helps us to make the game frame-independent. That is, regardless of the fps, the game will be executed at the same speed. Let’s understand what this means:

Suppose, our game runs at 60 fps. It means that the game is updating 60 times per second, in other words, there are 60 frames.

Note: FPS stands for frames per second

Now, let’s have a look at to the time between frames:

Firstly, the game start, frame 1 is executing, then frame 1 finish, so frame 2 is executing. Time.deltaTime started to calculate when frame 1 ends and finished calculating when frame 2 ends. Let’s see the image below to understand it:

Что такое time deltatime. Смотреть фото Что такое time deltatime. Смотреть картинку Что такое time deltatime. Картинка про Что такое time deltatime. Фото Что такое time deltatime

Note: Its value is changing continuously, for this example, I just used 0.05

As we understood what does that mean, let’s see the usage of it and why we are using it:

Always, when we want to move an object, no doubt we use an Update() method.

Note: Update() method is called once per frame

Источник

Какую основную функцию выполняет Time.deltaTime в Unity?

Я учусь разработке игр в Unity. Недавно я получил структуру для функции Time.deltaTime во время кода, который я изучал из учебников. Я искал об этом для лучшего понимания, но не понял основной цели его использования, как это объясняется на профессиональном уровне. Короче говоря, я хочу несколько простых объяснений. Итак, я могу понять из этого.

3 ответа

Рендеринг и выполнение скрипта требует времени. Это отличается каждый кадр. Если вы хотите

Чтобы обрабатывать кадры разной длины, вы получаете «Time.deltaTime». В Update он сообщит вам, сколько секунд прошло (обычно это доля, например, 0,00132), чтобы закончить последний кадр.

Если вы теперь переместите объект из A в B, используя этот код:

Это будет двигаться 0,05 единиц на кадр. После 100 кадров он переместился на 5 единиц.

Таким образом, вашему объекту потребуется 1-5 секунд, чтобы пройти это расстояние.

Но если вы сделаете это:

Он будет двигаться 5 единиц в 1 секунду. Независимо от частоты кадров. Потому что, если у вас есть 10000 кадров в секунду, deltaTime будет очень очень маленьким, поэтому он будет перемещаться лишь очень маленьким битом в каждом кадре.

Примечание. В FixedUpdate() он технически не на 100% одинаков для каждого кадра, но вы должны действовать так, как будто он всегда равен 0.02f или каков бы ни был установлен физический интервал. Независимо от частоты кадров Time.deltaTime в FixedUpdate() вернет fixedDeltaTime

Это свойство предоставляет время между текущим и предыдущим кадром.

Вы можете использовать это, например, для проверки частоты кадров. Также, как сказано здесь

Источник

What main function does Time.deltaTime perform in Unity?

I’m learning game development in Unity. I recently got struct to the Time.deltaTime function during the code i was learning from the tutorials. I have searched about it for better understanding but not learned the main purpose of using it as it is explained in a professional way. In short I want some easy explanation. So, I can understand from it.

3 Answers 3

Time.deltaTime is simply the time in seconds between the last frame and the current frame. Since Update is called once per frame, Time.deltaTime can be used to make something happen at a constant rate regardless of the (possibly wildly fluctuating) framerate.

So if we just say obj.transform.position += new Vector3(offset, 0, 0); in our update function then obj will move by offset units in the x direction every frame, regardless of FPS.
However if we instead say obj.transform.position += new Vector3(offset * Time.deltaTime, 0, 0); then we know that obj will move offset units every second as every frame it will move the fraction of offset corresponding to how much time that frame took.

Rendering and script execution takes time. It differs every frame. If you want

To handle different lenghts of frames, you get the «Time.deltaTime». In Update it will tell you how many seconds have passed (usually a fraction like 0.00132) to finish the last frame.

If you now move an object from A to B by using this code:

It will move 0.05 Units per frame. After 100 frames it has moved 5 Units.

Some pcs may run this game at 60fps, others at 144 hz. Plus the framerate is not constant.

So your object will take 1-5 seconds to move this distance.

But if you do this:

it will move 5 units in 1 second. Independent of the framerate. Because if you have 10000 fps the deltaTime will be very very small so it only moves a very tiny bit each frame.

Источник

Time.deltaTime in Unity3D

Что такое time deltatime. Смотреть фото Что такое time deltatime. Смотреть картинку Что такое time deltatime. Картинка про Что такое time deltatime. Фото Что такое time deltatime

It is very important for a Unity Developer to have a sound understanding of Time.deltaTime. Let us learn the basics of Time.deltaTime in Unity3D with some examples.

What is Time.deltaTime?

Time.deltaTime is the completion time in seconds since the last frame. It is read only. Therefore you cannot modify it! This property provides the time between the current and previous frame. But what does that mean?

We are aware of the Update method in Unity3D. Time.deltaTime in layman terms would be the time lapse between two update methods. Let’s say there are 10 lines of code in the Update Method. So, Time.deltaTime would determine how much time does it take to execute the lines of code in one frame. This property is a variable value as its value would depend upon how much time one frame takes to execute which further depends upon how much lines of code needs to be executed.

Time.deltaTime in relation with fps

FPS is frames per second and the time taken for completion of one frame is Time.deltaTime. In other words, we can say,

Therefore, when fps is 60, Time.deltaTime is = 0.0166666 seconds

Usage of Time.deltaTime in Unity3D

Creating a Timer

Smooth Translation of an object independent of Frame Rate

Let us use static speed for translation of an object for movement in x-axis, lets say speed = 5 as below:

Lets test the lines of code on a device with fps equal to 60 (i.e. 60 frames in one second). The object moves 5 units in 1 frame(as speed=5). The distance moved by object in 60 frames or 1 second is 60*5 = 300 units

Now, lets test this code on a device with fps equal to 30. The object still moves 5 units in 1 frame as speed = 5. However, the distance moved by object in 30 frames or 1 second is 30*5 = 150 units.

Therefore, using static value, an object on a device with higher fps moves faster than that on a lower fps device, which is not what is desired.

Lets see what happens when we use Time.deltaTime.

The above line of code gives a smooth translation in x-axis as the object will always move independent of the Time Frame i.e. if the fps falls low or high, the translation is linear.

Lets say the fps is 60, i.e. 60 frames in one second. Time for each frame is 0.016666666 as explained formerly. The distance moved by object in 1 second is 1 unit(0.0166666*60 frames)

If the fps is 30, i.e. 30 frames in one second, time for each frame is 0.03333. The distance moved by object in 1 second is 1 unit(0.03333*30 frames)

Therefore, the object moves over the same distance irrespective of the device performance.

Источник

Русские Блоги

время

Time.Deltatime Я считаю, что все использовали это, и сегодня я проанализирую что-то, связанное с DeltaTime

1. Понимание по определению

Unity3D официальный сайтПравильный Time.Deltatime Учитывая это описание:

The time in seconds it took to complete the last frame (Read Only).

То есть для предыдущего кадра время от начала до конца равно Time.DeltaTime. Мы также можем понять это так:

После обработки этой строки кода в последнем кадре мы возвращаемся к этой строке кода в этом кадре, и время прошло Time.DeltaTime секунд.

Кроме того, согласно определению, мы не трудно ввести, Time.Deltatime Должно бытьСек / кадр

2. Понимание в использовании

вUnity3D официальный сайтНа это также есть предложение:

If you add or subtract to a value every frame chances are you should multiply with Time.deltaTime. When you multiply with Time.deltaTime you essentially express: I want to move this object 10 meters per second instead of 10 meters per frame.

Значение примерно, если вы хотите определить объект каждыйвторойДвигайтесь 10 метров вместо каждогоРамкаДвигайся 10 метров. Пожалуйста, умножьте DeltaTime после 10, чтобы он стал10 m/s

Может быть, в первый раз, когда вы почувствуете, что это предложение немного волшебно, как вы можете умножить DeltaTime, чтобы заставить объект двигаться в зависимости от времени?

Предположим теперь, что есть переменная скорость = 10 м / с, есть надежда, что во время воспроизведения объект будет двигаться в соответствии с этой скоростью. Итак, когда мы сфокусировались на методе Update, мы подумали о том, какое расстояние нам нужно пройти в каждом кадре, чтобы имитировать скорость движения в реальном состоянии? То есть рассчитать X м / кадр.

От предыдущего кадра к этому кадру время прошло в секундах DeltaTime, и истинная скорость движения составляет 10 м / с, поэтому за истекшее время объект должен двигаться на расстояние DeltaTime * 10, и Это расстояние в точности равно расстоянию, перемещенному от предыдущего кадра к этому кадру.

Согласно этой идее, следующая формула может быть перечислена:

10 м / с × DeltaTime s / frame = X м / frame

И эта формула как раз и есть метод использования, предложенный на официальном сайте.

3.1 Внимание понимание

Unity3D официальный сайтЕсть также некоторые меры предосторожности:

When called from inside MonoBehaviour’s FixedUpdate, returns the fixed framerate delta time.

Сначала напишите код скрипта:

Затем вы можете запустить, чтобы увидеть эффект:

Что такое time deltatime. Смотреть фото Что такое time deltatime. Смотреть картинку Что такое time deltatime. Картинка про Что такое time deltatime. Фото Что такое time deltatime

Посредством наблюдения было обнаружено, что время, отображаемое с помощью FixedUpdate, является установленным фиксированным значением 0,02 секунды, и обновление не обязательно, но оно намного меньше времени, отображаемого с помощью FixedUpdate. Таким образом, мы можем заключить, что FixedUpdate также может быть использован напрямую Time.DeltaTime 。

Почему Time.DeltaTime Разные методы могут возвращать разные значения, как этого добиться. Пока я не знаю, я надеюсь, что читатели, у которых есть идеи для реализации, могут оставить сообщение и обменяться.

Note that you should not rely on Time.deltaTime from inside OnGUI since OnGUI can be called multiple times per frame and deltaTime would hold the same value each call, until next frame where it would be updated again.

Смысл не в том, чтобы использовать DeltaTime в OnGUI, потому что OnGUI может вызываться несколько раз в одном кадре. Что касается того, почему вы должны обращать на это внимание в принципе, я считаю, что читатели, которые внимательно прочитали вышеуказанное содержание, могут иметь глубокое понимание.

4. Вывод

Зачем усердно работать и думать о начале. —— Чжоу Синчи

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *