Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
可覆盖函数
Godot 的 Node 类提供了一些虚函数,你可以通过覆盖这些虚函数来在每帧或发生特定事件时更新节点,比如节点进入场景树时就有一个虚函数会被调用。
本文档中会向大家展示经常会用到的那些虚函数。
参见
这些函数在引擎内部会依赖 Godot 的底层通知系统而调用。要了解、学习相关知识,请参阅 Godot 通知。
除了类的构造函数之外,还有两个函数可以用来进行初始化操作及获取节点操作:_enter_tree()
和 _ready()
。
节点进入场景树时就会激活,引擎会调用其 _enter_tree()
方法,此时该节点的子节点可能还未激活,由于你可以从场景树中移除节点然后重新添加这个节点,因此在一个节点的生命周期内,这个函数可能会被调用多次。
在大多数时候,你用的初始化函数其实都是 _ready()
。这个函数只会在节点的生命周期中调用一次,且会在 _enter_tree()
执行完毕之后调用。_ready()
可以保证所有子节点都已进入场景树,因此在该节点内可以安全地调用 get_node()
。
参见
要学习更多有关节点引用的知识,请参阅 节点与场景实例。
另一个有关的回调函数便是 _exit_tree()
,在节点退出场景树时,引擎便会调用该节点的该函数,调用时机既可以是你调用 Node.remove_child() 的时时候,也可以是你释放这个节点的时候。
# Called every time the node enters the scene tree.
func _enter_tree():
pass
# Called when both the node and its children have entered the scene tree.
func _ready():
pass
# Called when the node is about to leave the scene tree, after all its
# children received the _exit_tree() callback.
func _exit_tree():
pass
// Called every time the node enters the scene tree.
public override void _EnterTree()
{
base._EnterTree();
}
// Called when both the node and its children have entered the scene tree.
public override void _Ready()
{
base._Ready();
}
// Called when the node is about to leave the scene tree, after all its
// children.
public override void _ExitTree()
{
base._ExitTree();
}
虚函数 _process()
和 _physics_process()
可以分别用来对节点进行每帧更新和每物理帧更新。要了解更多信息,请阅读专门介绍空闲帧和物理帧的文档:空闲处理与物理处理。
# Called every frame.
func _process(delta):
pass
# Called every physics frame.
func _physics_process(delta):
pass
public override void _Process(double delta)
{
// Called every frame.
base._Process(delta);
}
public override void _PhysicsProcess(double delta)
{
// Called every physics frame.
base._PhysicsProcess(delta);
}
还有两个关键的内置节点回调函数 Node._unhandled_input() 和 Node._input(),二者都可用来接收、处理单独的输入事件。如果按键、鼠标点击等事件没有被 _input()
回调函数或用户界面组件处理,那么_unhandled_input()
方法就会接收到该事件,游戏中的输入通常是使用后者进行处理的。_input()
回调函数可以用来在 _unhandled_input()
获取输入事件之前拦截并处理输入事件。
要学习更多关于 Godot 中输入的内容,请参阅输入章节。
# Called once for every event.
func _unhandled_input(event):
pass
# Called once for every event before _unhandled_input(), allowing you to
# consume some events.
func _input(event):
pass
// Called once for every event.
public override void _UnhandledInput(InputEvent @event)
{
base._UnhandledInput(@event);
}
// Called once for every event before _UnhandledInput(), allowing you to
// consume some events.
public override void _Input(InputEvent @event)
{
base._Input(@event);
}
还有 Node._get_configuration_warning() 等更多的可覆盖函数。特定的节点类型也会提供很多的回调函数,比如 CanvasItem._draw() 可以用来用程序绘图,Control._gui_input() 可以用来处理 UI 元素上的点击和输入事件,等等。