Godot Engine-生命週期與輸入處理
阿新 • • 發佈:2019-01-01
Godot的生命週期方法都以下劃線"_"開始,因此在內建Editor中先輸入"_"即可彈出提示
extends KinematicBody2D var speed = 0.0 var motion = Vector2() func _ready(): # Called when the node is added to the scene for the first time. # Initialization here pass func _process(delta): if Input.is_action_just_pressed("ui_right"): print("Input Right") pass if Input.is_action_pressed("ui_left"): print("Input Left") pass pass func _physics_process(delta): #To manage the logic of a kinematic body or character, # it is always advised to use physics process, pass func _input(event): if event.is_pressed() and event.is_action_pressed("mouse_button_left"): print("Input mouse_button_left") pass pass
_ready:相當於Unity中的Start用於初始化
func _ready():
# Called when the node is added to the scene for the first time.
# Initialization here
pass
_process:相當於Unity的Update,其中delta用於平衡FPS
#func _process(delta): # # Called every frame. Delta is time since last frame. # # Update game logic here. # pass
_physics_process:類似於Unity裡的FixedUpdate,貌似以前的版本就叫_fixed_process
func _physics_process(delta):
#To manage the logic of a kinematic body or character,
# it is always advised to use physics process,
pass
另外,舊版本中這兩個process方法要在_ready方法中set_process(true)和set_physics_process(true)來開啟呼叫,3.0版本以後是預設為true的
輸入處理有如下兩種:
1類似Unity一樣放到process裡在每一幀用If語句判斷
2在_input裡使用事件觸發的回撥函式
形式上第二種可以把處理輸入的邏輯單獨拿出來並且等到有輸入事件時再執行而不用每一幀都判斷一次,但是簡單用了一下發現,_input型別不能區分按鍵持續按下的事件
func _process(delta):
if Input.is_action_just_pressed("ui_right"):
print("Input Right")
pass
if Input.is_action_pressed("ui_left"):
print("Input Left")
pass
pass
func _input(event):
if event.is_pressed() and event.is_action_pressed("mouse_button_left"):
print("Input mouse_button_left")
pass
pass