1. 程式人生 > >GODOT遊戲程式設計005---- Scripting(2)

GODOT遊戲程式設計005---- Scripting(2)

Scripting (continued)
http://docs.godotengine.org/en/3.0/getting_started/step_by_step/scripting_continued.html


在godot中很多動作都是有反饋或虛擬函式觸發,所以沒必要每次都寫程式碼there is no need to write code that runs all the time.。
但是在每個frame(幀?)中都需要程式碼被處理,有兩種方式處理:空閒處理和物理處理。 idle processing and physics processing.
當代碼中 Node._process() 被發現時會啟用空閒處理,可以通過 Node._process() 的功能開啟或關閉。
物理處理取決於每秒幀數,當換幀時被啟用。

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

delta引數包含時間流逝。The delta parameter contains the time elapsed in seconds, as a floating point
這個引數可以用來保證物體按相同時間量而不是遊戲FPS。如在移動的時候,希望移動速度相同而不以幀率為準。
通過_physics_process()進行的物理處理與上面類似,它總是在物理距離physics step之前,總在固定時間間隔預設一秒60次。你可以更改專案設定來設定間隔,Physics -> Common -> Physics Fps.。
然而,_process()函式不和物理同步,它的幀率不是常數,而是取決於硬體和遊戲優化,執行於物理距離之後。
一個簡單的驗證方法是建立一個只有一個標籤Label的場景,輸入程式碼:

extends Label

var accum = 0

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

Groups分組
節點可以加入分組,這是一個組織大型場景的有用特色。有兩種方法實現,一是從介面:
這裡寫圖片描述
二是通過程式碼。

Notifications通知
Overrideable functions

建立節點Creating nodes
可以用.new()新建節點。

var s
func _ready():
    s = Sprite.new
() # Create a new sprite! add_child(s) # Add it as a child of this node.

刪除節點free()

func _someaction():
    s.free() # Immediately removes the node from the scene and frees it.

當一個節點被刪除,它的所有子節點也被刪除。
有時我們想刪除一個節點時它正被“鎖定blocked”,因為它正發射訊號或呼叫函式。這會使遊戲崩潰,debugger經常發生。
安全的方法是用Node.queue_free()來在空閒時刪除。

func _someaction():
    s.queue_free() # Queues the Node for deletion at the end of the current Frame.

Instancing scenes引用場景
引用場景程式碼分為兩步,一是從硬碟載入

var scene = load("res://myscene.tscn") # Will load when the script is instanced.

在解析時預載入會更方便。

var scene = preload("res://myscene.tscn") # Will load when parsing the script.

但場景並不是節點,它被打包在 PackedScene。為了建立實際的節點, PackedScene.instance() 函式必須被呼叫。

var node = scene.instance()
add_child(node)

這兩步,對快速引用敵人、武器什麼的很有用。


上面這些,額,缺乏直觀感受,下一篇繼續。