【Unity】 Time.deltatime 該怎麼用

Time.deltatime

官方文件

https://docs.unity3d.com/ScriptReference/Time-deltaTime.html

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

When this is called from inside MonoBehaviour.FixedUpdate, it returns Time.fixedDeltaTime.

翻譯翻譯

  • Frame
    • 中文常用每一幀

簡單來說就是每台執行程式的電腦不一樣
所以每秒的幀數不一樣

所以在一般的情況來說,Time.deltaTime 就是只「一幀花了幾秒」

所以我們如果有一個速度 v 是每秒移動多少,
那 v deltaTime 就會是 每幀移動多少,
所以在 Update() 中就可以取用 v
deltaTime 就可以獲得正確的顯示位移量。

所以不管是距離的速度、還是角度的速度
如果在 Update() 中要運算,基本上都是
速度 * Time.deltaTime() 來取得 這一幀的改變量

為什麼 在 FixUpdate() 中的值會不一樣

因為 FixUpdate() 是一個跟 顯示幀不相關的時間點,
FixUpdate() 主要是拿來精確計算物理變化使用的,
所以 每一幀只會發生一次 Update(),但可能發生 0次或多次的 FixUpdate(),所以在 FixUpdate() 中,Time.deltaTime 就變成了 上一次 完成 FixUpdate() 花了幾秒

實際用法

官方範例

using UnityEngine;
// Rotate around the z axis at a constant speed
public class ConstantRotation : MonoBehaviour
{
    public float degreesPerSecond = 2.0f;
    void Update()
    {
        transform.Rotate(0, 0, degreesPerSecond * Time.deltaTime);
    }
}

相關文章

【Unity】Update、FixedUpdate、LateUpdate 的差異

參考資料
關於

登山嚮導 / IT / 武術/網頁工程 - 貪多而正努力咀嚼的人生小吃貨