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)

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


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章