可覆写的函数与创建节点

以下所描述的这些可覆写的函数,能够应用于节点:

func _enter_tree():
    # When the node enters the _Scene Tree_, it becomes active
    # and  this function is called. Children nodes have not entered
    # the active scene yet. In general, it's better to use _ready()
    # for most cases.
    pass

func _ready():
    # This function is called after _enter_tree, but it ensures
    # that all children nodes have also entered the _Scene Tree_,
    # and became active.
    pass

func _exit_tree():
    # When the node exits the _Scene Tree_, this function is called.
    # Children nodes have all exited the _Scene Tree_ at this point
    # and all became inactive.
    pass

func _process(delta):
    # This function is called every frame.
    pass

func _physics_process(delta):
    # This is called every physics frame.
    pass

如前所诉,用这些函数替代通知系统是更好的选择。

创建节点

如果要用代码方式创建一个节点, 只需调用 .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.

当一个节点被释放时, 它也会释放其所有子节点。因此, 手动删除节点比看起来简单得多。释放基节点, 那么子树中的其他所有东西都会随之消失。

当我们要删除一个当前处于“阻塞”状态的节点时,就可能发生这种情况, 因为此时它正在发出信号或者在调用一个函数。这会导致游戏崩溃。使用调试器运行Godot通常能捕获这种情况并向你发出警告。

删除一个节点最安全的方法是使用 Node.queue_free()。这会在程序空闲时安全地擦除该节点。

func _someaction():
    s.queue_free() # Removes the node from the scene and frees it when it becomes safe to do so.

 

posted @ 2018-12-30 17:48  宸少凌  阅读(242)  评论(0编辑  收藏  举报

万年以来谁著史,三千里外欲封侯