Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

空閒處理與物理處理

Games run in a loop. Each frame, you need to update the state of your game world before drawing it on screen. Godot provides two virtual methods in the Node class to do so: Node._process() and Node._physics_process(). If you define either or both in a script, the engine will call them automatically.

Godot 中需要的圖示有兩種型別:

  1. **空閒處理**(Idle processing)可以用來執行每影格更新節點的程式碼,執行頻率會盡可能地快。

  2. **物理處理**(Physics processing)的頻率是固定的,預設為每秒 60 次。它和遊戲的實際影格率無關,可以讓物理平滑執行。任何與物理引擎相關的東西都應該用它,比如移動可能與環境相碰撞的實體。

閒置處理會在腳本中有 Node._process() 方法來開啟或關閉閒置處理。

每次引擎需要繪製一影格的時候就會呼叫該方法:

func _process(delta):
    # Do something...
    pass

有一點很重要的是, _process() 的呼叫頻率會依據應用程式在執行時的 FPS (Frames Per Second,每秒影格數) 而定。這個頻率在不同裝置下可能會不同。

函式的參數 delta 是從上一次呼叫 _process() 開始所經過的秒數。借助這個參數就可以進行與影格率無關的計算。例如,為移動物理做動畫時,應該始終將速度值乘上 delta

使用 _physics_process() 來進行物理處理,但物理處理是在每個物理步驟前使用的,如控制角色。物理處理永遠都在物理步驟之前執行,而且會以相同的間隔呼叫,預設為每秒 60 次。可以在專案設定中的 [Physics] -> [Common] -> [Physics FPS] 來更改這個間隔。

每次引擎需要繪製一影格的時候就會呼叫該方法:

func _physics_process(delta):
    # Do something...
    pass

然而,_process() 函式並不與物理處理同步。_process() 的影格率並不固定,且會根據硬體與遊戲的最佳化而有所不同。在單一執行緒的遊戲上,_process() 會在物理步驟後才被執行。

有一個簡單的方法可以讓我們瞭解 _process()。先建立一個有 Label 節點的場景,然後使用下列腳本:

extends Label

var time = 0

func _process(delta):
    time += delta
    text = str(time) # 'text' is a built-in Label property.

這樣就會顯示一個每一影格都會增加的計數器。