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, as often as possible.
func _process(delta):
pass
# Called every physics frame.
func _physics_process(delta):
pass
public override void _Process(double delta)
{
// Called every frame, as often as possible.
base._Process(delta);
}
public override void _PhysicsProcess(double delta)
{
// Called every physics frame.
base._PhysicsProcess(delta);
}
还有两个关键的内置节点回调函数 Node._input() 和 Node._unhandled_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 _unhandled_input(), allowing you to
// consume some events.
public override void _Input(InputEvent @event)
{
base._Input(@event);
}
There are some more overridable functions like Node._get_configuration_warnings(). Specialized node types provide more callbacks like CanvasItem._draw() to draw programmatically or Control._gui_input() to handle clicks and input on UI elements.